﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.DAL.Context;
using RN.ERP.Entity.ZBDLRY;
using RN.ERP.BLL.LC.Utilities;
using System.Transactions;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Configuration;
using Newtonsoft.Json;
using Fly.FlyCommon;
using Fly.Log;
using Fly.Common.Linq;
using RN.ERP.DTO;
using RN.ERP.DAL;
using System.Reflection;
using FlowCommon = Fly.Common.WorkFlow;
using System.Data;
using System.Data.Entity;
using System.Text.RegularExpressions;
using Fly.Common.WorkFlow;

namespace RN.ERP.BLL.LC
{
    public class EnterpriseBLL : BaseEnterpriseBLL
    {
        private const string OutProvinceAreaCode = "18";
        #region dbContext
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }
        public EnterpriseBLL()
        {
            base.baseContext = new ZBDL_Context();
        }
        #endregion

        private LogAndFlowHelper baseBll = new LogAndFlowHelper();

        public override string GetCorpQualities(string corpUserGuid, string areaCode)
        {
            Guid guid;
            List<tb_Corp_Quality_Zbdlry> ret = new List<tb_Corp_Quality_Zbdlry>();
            if (!Guid.TryParse(corpUserGuid, out guid))
            {
                return JsonConvert.SerializeObject(ret);
            }

            ret = dbContext.Corp_CompanyQualities.Where(m => m.CorpUserGuid == guid).OrderByDescending(m1 => m1.IsMain).ToList();
            int cnt = ret.Count;
            return JsonConvert.SerializeObject(ret);
        }
        public override string GetCorpQuality(string qualityId, string areaCode)
        {
            Guid qualityGuid = Guid.Empty;
            if (Guid.TryParse(qualityId, out qualityGuid))
            {
                tb_Corp_Quality_Zbdlry quality = dbContext.Corp_CompanyQualities.SingleOrDefault(q => q.QualityGuid == qualityGuid);
                return JsonConvert.SerializeObject(quality);
            }
            else
            {
                return string.Empty;
            }
        }
        public override string GetCorpInfo(string corpUserGuid, string areaCode)
        {
            Guid guid;
            int CorpID = 0;
            Tb_Corp_CompanyInfo_Zbdl ret = new Tb_Corp_CompanyInfo_Zbdl();

            using (ZBDL_Context db = new ZBDL_Context())
            {
                if (Int32.TryParse(corpUserGuid, out CorpID))
                {
                    ret = db.Corp_CompanyInfos.FirstOrDefault(m => m.ID == CorpID);
                }
                else if (Guid.TryParse(corpUserGuid, out guid))
                {
                    ret = db.Corp_CompanyInfos.FirstOrDefault(m => m.CorpUserGuid == guid);
                }
                else
                {
                    return JsonConvert.SerializeObject(ret);
                }
                return JsonConvert.SerializeObject(ret);
            }
        }
        /// <summary>
        /// 验证企业是否存清出市场
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override string CheckCorp(string dogId, string areaCode)
        {
            ////1、企业信息 检查:未删除、审核通过、bCanBid包含4，如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
            ////2、考核结果 检查对应资质的分数是否低于<60分
            string result = string.Empty;
            if (string.IsNullOrEmpty(dogId))
            {
                result = "1,企业狗号不能为空！";
                return JsonConvert.SerializeObject(result);
            }
            else
            {
                try
                {
                    int dogCode;
                    int.TryParse(dogId, out dogCode);
                    // Orderby 为报名时不取出代理企业
                    T_Sys_Users_Zbdl users = dbContext.T_Sys_Users.Where(m => m.DogID == dogCode).OrderBy(m => m.RoleID).FirstOrDefault();

                    if (users == null)
                    {
                        result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！(1)";
                    }
                    else
                    {
                        ////1、企业信息 检查:未删除、审核通过、清除市场、停止招标2013-5-29修改
                        Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(m => m.CorpUserGuid == users.UserGuid && m.IsDel == false).FirstOrDefault();
                        if (corp == null)
                        {
                            result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！(2)";
                        }
                        else
                        {
                            result = "0,合格。";
                            //string area = System.Configuration.ConfigurationManager.AppSettings["Area"];
                            if (areaCode == "10")
                            {
                                Guid CorpGuid = corp.CorpGuid;
                                int AppID = GetAppID(areaCode);
                                CMFlow_Zbdl cmflow = dbContext.CMFlow.Where(c => c.AppID == AppID && c.EntityID == CorpGuid && c.FlowCode.StartsWith("1")).FirstOrDefault();
                                if (cmflow == null)
                                {
                                    result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！(3)";
                                }
                                else
                                {
                                    List<FlEntityCredit_Zbdl> entityList = dbContext.FlEntityCredit.Where(c => c.appid == AppID && c.EntityID == CorpGuid).ToList();
                                    foreach (FlEntityCredit_Zbdl entity in entityList)
                                    {
                                        if (entity.Denied == "是")
                                        {
                                            result = "1,该企业已被主管清出市场！";
                                            break;
                                        }
                                        if (entity.StopBid == "是" && entity.StopBegionTime <= DateTime.Now && entity.StopEndTime >= DateTime.Now)
                                        {
                                            result = "1,该企业已被主管停止投标！";
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (!corp.FlowCode.StartsWith("1"))
                                {
                                    result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！";
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = "1," + ex.Message;
                }
            }
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 地区编号和操作编号对应表
        /// </summary>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private int GetAppID(string areaCode)
        {
            IDictionary<string, int> area = new Dictionary<string, int>();
            area.Add("00", 150);
            area.Add("02", 152);
            area.Add("05", 155);
            area.Add("06", 157);
            area.Add("10", 160);
            if (area.ContainsKey(areaCode))
            {
                return area[areaCode];
            }
            return 0;
        }
        /// <summary>
        /// 根据企业Guid验证企业是否存清出市场
        /// </summary>
        /// <param name="corpGuid"></param>
        /// <returns></returns>
        public override string CheckCorpByCorpGuid(string corpGuid, string areaCode)
        {
            ////1、企业信息 检查:未删除、审核通过、bCanBid包含4，如果是外地入青企业，检查外地入青证（Tb_Corp_CompanyInfo_wdrq）的有效期是否过期
            ////2、考核结果 检查对应资质的分数是否低于<60分
            string result = string.Empty;
            Guid cid;
            if (string.IsNullOrEmpty(corpGuid))
            {
                result = "1,企业信息有误！";
                return JsonConvert.SerializeObject(result);
            }
            if (!Guid.TryParse(corpGuid, out cid))
            {
                result = "1,企业信息格式不正确！";
                return JsonConvert.SerializeObject(result);
            }
            if (string.IsNullOrEmpty(areaCode) || areaCode.Length < 2)
            {
                result = "1,地区编号信息格式不正确！";
                return JsonConvert.SerializeObject(result);
            }
            try
            {
                ////1、企业信息 检查:未删除、审核通过、清除市场、停止招标2013-5-29修改
                var dbCompanyInfo = dbContext.Corp_CompanyInfos;
                Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(m => m.CorpGuid == cid && m.IsDel == false).FirstOrDefault();
                if (corp == null)
                {
                    result = "1,该企业不存在，请检查接入数字设备是否正确！";
                    return JsonConvert.SerializeObject(result);
                }
                result = "0,可以报名。";

                string areaCode2 = areaCode.Substring(0, 2);
                //string area = System.Configuration.ConfigurationManager.AppSettings["Area"];
                if (areaCode2 == "10")
                {
                    Guid CorpGuid = corp.CorpGuid;
                    // int AppID = GetAppID(corp.AreaCode.Substring(0, 2));
                    int AppID = GetAppID(areaCode2);
                    CMFlow_Zbdl cmflow = dbContext.CMFlow.Where(c => c.AppID == AppID && c.EntityID == CorpGuid && c.FlowCode.StartsWith("1")).FirstOrDefault();
                    if (cmflow == null)
                    {
                        result = "1,该企业不存在或尚未通过审核，请检查接入数字设备是否正确！";
                    }
                    else
                    {
                        List<FlEntityCredit_Zbdl> entityList = dbContext.FlEntityCredit.Where(c => c.appid == AppID && c.EntityID == CorpGuid && c.IsDel == 0).ToList();
                        foreach (FlEntityCredit_Zbdl entity in entityList)
                        {
                            if (entity.Denied == "是")
                            {
                                result = "1,该企业已被主管清出市场！";
                                break;
                            }
                            if (entity.StopBid == "是" && entity.StopBegionTime <= DateTime.Now && entity.StopEndTime >= DateTime.Now && !string.IsNullOrEmpty(entity.StopBidArea) && entity.StopBidArea.Contains(areaCode))
                            {
                                result = "1,该企业已被主管停止投标！";
                                break;
                            }
                        }
                    }
                }
                else
                {
                    #region 验证企业在该市场是否审核通过 新结构 2013-10-17修改 by毛凯
                    string corpUserGuid = corp.CorpUserGuid.ToString();
                    string refArea = areaCode.Substring(0, 2);
                    var flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && (f.IsDel == null || f.IsDel == false) && f.AreaCode.StartsWith(refArea)).FirstOrDefault();
                    if (flowCode == null || !flowCode.FlowCode.StartsWith("1"))
                    {
                        result = "1,该企业不存在或尚未在项目所在地通过审核，请检查接入数字设备是否正确！";
                    }
                    #endregion
                    //if (!corp.FlowCode.StartsWith("1") || (corp.AreaCode2.Substring(0, 2) != areaCode2 && corp.AreaCode.Substring(0, 2) != areaCode2))
                    //{
                    //    result = "1,该企业不存在或尚未在项目所在地通过审核，请检查接入数字设备是否正确！";
                    //}
                }

            }
            catch (Exception ex)
            {
                result = "1," + ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }
        #region 查询
        public override bool IsOrgnizationCodeExists(string orgnizationCode, string corpType, string areaCode)
        {
            int count = dbContext.Corp_CompanyInfos.Count(c => c.OrginazationCode == orgnizationCode && c.Type == corpType);
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public override bool IsUserExisted(string userName)
        {
            int count = dbContext.T_Sys_Users.Count(t => t.UserName == userName);
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override OperationResult CorpRegister(
            Tb_Corp_CompanyInfo corp,
            T_Sys_Users user,
            bool isReturnModel,
            string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.ReturnValue = 0;
            result.Result = false;
            result.Message = "注册失败";
            Tb_Corp_Embranchment_Zbdl em = new Tb_Corp_Embranchment_Zbdl();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    //添加用户信息
                    Entity.ZBDLRY.T_Sys_Users_Zbdl userInfo = new T_Sys_Users_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(user, userInfo);
                    userInfo.AreaCodeScope = userInfo.AreaCode;
                    Guid gid = Guid.NewGuid();
                    userInfo.UserGuid = gid;
                    dbContext.T_Sys_Users.Add(userInfo);
                    //添加企业信息
                    Entity.ZBDLRY.Tb_Corp_CompanyInfo_Zbdl corpInfo = new Tb_Corp_CompanyInfo_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(corp, corpInfo);
                    corpInfo.CorpGuid = Guid.NewGuid();
                    corpInfo.CorpUserGuid = gid;
                    corpInfo.FlowCode = "0";
                    switch (userInfo.RoleID)
                    {
                        case 15:
                            corpInfo.classID = 2501;
                            break;
                        case 42:
                            corpInfo.classID = 2502;
                            break;
                        case 45:
                            corpInfo.classID = 2505;
                            break;
                        case 47:
                            corpInfo.classID = 2507;
                            break;
                        case 48:
                            corpInfo.classID = 2508;
                            break;
                        case 49:
                            corpInfo.classID = 2509;
                            break;
                        case 46:
                            corpInfo.classID = 2500;
                            break;
                    }
                    if (corpInfo.IsDel == null)
                    {
                        corpInfo.IsDel = false;
                    }
                    dbContext.Corp_CompanyInfos.Add(corpInfo);
                    dbContext.SaveChanges();
                    //添加市场区域信息
                    em.AreaCode = corpInfo.AreaCode.Substring(0, 2);
                    em.IsNative = true;
                    em.CorpGuid = corpInfo.CorpGuid;
                    em.CorpUserGuid = corpInfo.CorpUserGuid;
                    em.BranchName = corpInfo.CorpName;
                    em.IsrtDate = DateTime.Now;
                    em.Address = corpInfo.Address;
                    em.BranchGid = Guid.NewGuid();
                    dbContext.CorpEmbranchment.Add(em);
                    //添加审核记录
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl model = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = corpInfo.AreaCode.Substring(0, 2),
                        CodeType = corpInfo.classID,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = corpInfo.CorpUserGuid.ToString(),
                        UpdateTime = DateTime.Now
                    };
                    baseBll.AddFlowcode(model);
                    //添加日志
                    baseBll.InsertUserLog("企业注册", corpInfo.ID.ToString(), corpInfo.classID.ToString(), "1");
                    dbContext.SaveChanges();
                    tran.Commit();
                    result.Message = "添加成功。";
                    result.Result = true;
                    result.ReturnValue = 1;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "添加失败：" + ex.InnerException; ;
                    result.Result = false;
                    result.ReturnValue = -1;
                }
            }
            return result;
        }

        public override DTO.OperationResult CorpReg(DTO.Tb_Corp_CompanyInfo corp, DTO.T_Sys_Users user)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.ReturnValue = 0;
            result.Result = false;
            result.Message = "注册失败";
            T_Sys_Users_Zbdl reguser = new T_Sys_Users_Zbdl();
            Tb_Corp_Embranchment_Zbdl em = new Tb_Corp_Embranchment_Zbdl();
            DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection;
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    //添加用户信息
                    Entity.ZBDLRY.T_Sys_Users_Zbdl userInfo = new T_Sys_Users_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(user, userInfo);
                    userInfo.AreaCodeScope = "14";
                    Guid gid = Guid.NewGuid();
                    userInfo.UserGuid = gid;
                    userInfo.Role = "15";
                    userInfo.RoleID = 15;
                    userInfo.bGrade = 15;
                    dbContext.T_Sys_Users.Add(userInfo);
                    //添加企业信息
                    Entity.ZBDLRY.Tb_Corp_CompanyInfo_Zbdl corpInfo = new Tb_Corp_CompanyInfo_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(corp, corpInfo);
                    corpInfo.CorpGuid = Guid.NewGuid();
                    corpInfo.CorpUserGuid = gid;
                    corpInfo.FlowCode = "0";
                    OperationResult isUrban = UrbanVerify(corpInfo.AreaCode);
                    if (isUrban.Result)
                    {
                        if (!(Boolean)isUrban.ReturnValue)
                        {
                            corpInfo.classID = corpInfo.classID * 10;
                        }
                    }

                    ////添加用户角色。
                    string sRoleId = userInfo.RoleID.ToString();
                    Entity.Authority.T_Sys_Roles role = dbContext.SysRoles.FirstOrDefault(r => r.Code == sRoleId && r.IsDel == false);
                    if (role != null)
                    {
                        dbContext.SysUserRoles.Add(new Entity.Authority.T_Sys_UserRole()
                        {
                            IsDel = false,
                            IsrtDate = DateTime.Now,
                            IsrtUseID = userInfo.UserGuid,
                            RoleGuid = role.RoleGuid,
                            UserGuid = userInfo.UserGuid
                        });
                    }
                    if (corpInfo.IsDel == null)
                    {
                        corpInfo.IsDel = false;
                    }
                    dbContext.Corp_CompanyInfos.Add(corpInfo);
                    dbContext.SaveChanges();
                    //添加市场区域信息
                    em.AreaCode = corpInfo.AreaCode.Substring(0, 2);
                    em.IsNative = true;
                    em.CorpGuid = corpInfo.CorpGuid;
                    em.CorpUserGuid = corpInfo.CorpUserGuid;
                    em.BranchName = corpInfo.CorpName;
                    em.IsrtDate = DateTime.Now;
                    em.Address = corpInfo.Address;
                    em.BranchGid = Guid.NewGuid();
                    dbContext.CorpEmbranchment.Add(em);
                    //添加审核记录
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl model = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = corpInfo.AreaCode.Substring(0, 2),
                        CodeType = corpInfo.classID,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = corpInfo.CorpUserGuid.ToString(),
                        UpdateTime = DateTime.Now
                    };
                    baseBll.AddFlowcode(model);
                    //添加日志
                    baseBll.InsertUserLog("企业注册", corpInfo.ID.ToString(), corpInfo.classID.ToString(), "1");
                    ////添加注册审核
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl flow = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = corpInfo.AreaCode.Substring(0, 2),
                        CodeType = 250114,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = corpInfo.CorpUserGuid.ToString(),
                        UpdateTime = DateTime.Now
                    };
                    baseBll.AddFlowcode(flow);
                    dbContext.SaveChanges();
                    tran.Commit();
                    result.Message = "添加成功。";
                    result.Result = true;
                    result.ReturnValue = 1;
                    reguser = userInfo;
                    con.Close();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    con.Close();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "添加失败：" + ex.InnerException; ;
                    result.Result = false;
                    result.ReturnValue = -1;
                }
            }
            OperationResult ret = CorpRegPost(reguser);
            if (ret.Result == false)
            {
                result.Message = ret.Message;
            }
            return result;
        }

        private OperationResult CorpRegPost(T_Sys_Users_Zbdl user)
        {
            OperationResult result=new OperationResult();
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = user.UserGuid.ToString();
            log.IsrtUserName = user.Name;
            log.IsrtUserArea = user.AreaCodeScope;
            log.IsrtUserRole = user.RoleID.ToString();
            log.FunctionId = "4";
            log.Content = "企业注册上报";
            result=CorpRegAudit(user.UserGuid.ToString(),user.AreaCodeScope,log,"0",string.Empty,false,"250114");
            return result;
        }
        #endregion

        #region 企业信息修改
        /// <summary>
        /// 企业信息修改
        /// </summary>
        /// <param name="corpInfo">企业基本信息</param>
        /// <param name="khCorpTable">安全生产许可证信息</param>
        /// <param name="embranchMent">分支机构信息</param>
        /// <param name="areaCode">当前市场</param>
        /// <returns></returns>
        public override DTO.OperationResult CorpEdit(DTO.Tb_Corp_CompanyInfo corpInfo
            , DTO.Kh_CorpTable khCorpTable
            , DTO.Tb_Corp_Embranchment embranchMent
            , string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            Tb_Corp_CompanyInfo_Zbdl dbCorpInfo = dbContext.Corp_CompanyInfos.Where(p => p.CorpUserGuid == corpInfo.CorpUserGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
            var user = dbContext.T_Sys_Users.Where(u => u.UserGuid == corpInfo.CorpUserGuid).FirstOrDefault();
            string corpId = corpInfo.CorpUserGuid.ToString();

            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            Tb_FlowCode_Zbdl flow = null;
            Tb_FlowCode_Zbdl currentEmbranchflow = null;
            Tb_FlowCode_Zbdl currentFlow = null;


            if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
            {
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && corpInfo.AreaCode.StartsWith(f.AreaCode)
                    && f.IsDel == false && f.AppID == appid).FirstOrDefault();
                currentEmbranchflow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && f.AreaCode == preArea
                    && f.IsDel == false && f.AppID == appid).FirstOrDefault();
                currentFlow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && (f.IsDel != true || f.IsDel == null)
                    && f.CodeType == dbCorpInfo.classID && f.AreaCode.StartsWith(preArea) && f.AppID == appid).FirstOrDefault();
            }
            else
            {
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && corpInfo.AreaCode.StartsWith(f.AreaCode) && f.IsDel == false).FirstOrDefault();
                currentEmbranchflow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && f.AreaCode == preArea && f.IsDel == false).FirstOrDefault();
                currentFlow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && (f.IsDel != true || f.IsDel == null) && f.CodeType == dbCorpInfo.classID && f.AreaCode.StartsWith(preArea)).FirstOrDefault();
            }

            Kh_CorpTable_Zbdlry khcorp = dbContext.SecurityInfo.Where(p => p.CorpUserGuid == dbCorpInfo.CorpUserGuid).FirstOrDefault();

            Tb_Corp_Embranchment_Zbdl embranchMentCorp = null;
            if (embranchMent != null)
            {
                embranchMentCorp = dbContext.CorpEmbranchment.Where(e => e.CorpUserGuid == dbCorpInfo.CorpUserGuid && e.AreaCode.StartsWith(embranchMent.AreaCode)).FirstOrDefault();
            }
            var checkReuslt = CheckCopInfo(corpInfo, khCorpTable, embranchMent);
            if (!checkReuslt.Result)
            {
                return checkReuslt;
            }
            //判断当前节点是否可操作
            var nextNode = new BasicBLL().GetNextFlowCode(user.RoleID.ToString(), "", areaCode, dbCorpInfo.classID.ToString(), currentFlow == null ? "" : currentFlow.FlowCode, FlowCommon.OptType.Edit);
            if (!nextNode.Result)
            {
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        ////1.修改Tb_Corp_CompanyInfo
                        if (dbCorpInfo != null)
                        {
                            if (dbCorpInfo.IsDel == null)
                            {
                                dbCorpInfo.IsDel = false;
                            }
                            ////判断企业在注册地是否审核通过，审核通过不允许修改基本信息和安全生产许可证
                            if (flow == null || !flow.FlowCode.StartsWith("1"))
                            {
                                Tb_Corp_CompanyInfo_Zbdl corpInfo_E = new Tb_Corp_CompanyInfo_Zbdl();
                                EntityHelper.ConvertEntity2OtherEntity(corpInfo, corpInfo_E);
                                EntityHelper.ConvertEntity2Entity<Tb_Corp_CompanyInfo_Zbdl>(corpInfo_E, dbCorpInfo);
                                ////2.添加或修改安全生产许可证（仅限施工企业）
                                string ids = "2501";
                                if (ConfigurationManager.AppSettings["SecurityIDS"] != null)
                                {
                                    ids = ConfigurationManager.AppSettings["SecurityIDS"].ToString();
                                }
                                string[] array = ids.Split(',');
                                if (array.Contains(dbCorpInfo.classID.ToString()))
                                {
                                    Kh_CorpTable_Zbdlry khCorpTable_E = new Kh_CorpTable_Zbdlry();
                                    EntityHelper.ConvertEntity2OtherEntity(khCorpTable, khCorpTable_E);
                                    if (khcorp != null)
                                    {
                                        EntityHelper.ConvertEntity2Entity<Kh_CorpTable_Zbdlry>(khCorpTable_E, khcorp);
                                    }
                                    else
                                    {
                                        dbContext.SecurityInfo.Add(khCorpTable_E);
                                    }
                                }
                            }
                            ////3.添加或修改分支机构
                            ////判断分支机构是否审核通过
                            if ((currentEmbranchflow == null || !currentEmbranchflow.FlowCode.StartsWith("1")) && embranchMent != null)
                            {
                                ////根据地区获取该地区是否已存在分支机构
                                Tb_Corp_Embranchment_Zbdl embranchMent_E = new Tb_Corp_Embranchment_Zbdl();
                                EntityHelper.ConvertEntity2OtherEntity(embranchMent, embranchMent_E);
                                if (embranchMentCorp != null)
                                {
                                    EntityHelper.ConvertEntity2Entity<Tb_Corp_Embranchment_Zbdl>(embranchMent_E, embranchMentCorp);
                                }
                                else
                                {
                                    embranchMent_E.BranchGid = Guid.NewGuid();
                                    if (embranchMent_E.CorpGuid == Guid.Empty || embranchMent.CorpGuid == null)
                                    {
                                        embranchMent_E.CorpGuid = corpInfo.CorpGuid;
                                    }
                                    dbContext.CorpEmbranchment.Add(embranchMent_E);
                                    ////新增分支机构则向tb_flowTable添加初始状态
                                    string strCorpUserGuid = corpInfo.CorpUserGuid.ToString();

                                    Tb_FlowCode_Zbdl curFlowCode = null;
                                    if ("06" == preArea)
                                    {
                                        curFlowCode = dbContext.FlowCodes.Where(f => f.ObjectId == strCorpUserGuid && f.CodeType == corpInfo.classID
                                            && f.AreaCode.StartsWith(preArea) && (f.IsDel == null || f.IsDel == false) && f.AppID == appid).FirstOrDefault();
                                    }
                                    else
                                        curFlowCode = dbContext.FlowCodes.Where(f => f.ObjectId == strCorpUserGuid && f.CodeType == corpInfo.classID && f.AreaCode.StartsWith(preArea) && (f.IsDel == null || f.IsDel == false)).FirstOrDefault();
                                    if (curFlowCode == null)
                                    {
                                        Tb_FlowCode_Zbdl flowCode = new Tb_FlowCode_Zbdl();
                                        flowCode.AreaCode = preArea;
                                        flowCode.ObjectId = corpId;
                                        flowCode.IsDel = false;
                                        flowCode.AppID = appid;
                                        flowCode.CodeType = dbCorpInfo.classID;
                                        flowCode.UpdateTime = DateTime.Now;
                                        flowCode.FlowCode = "0";
                                        dbContext.FlowCodes.Add(flowCode);
                                    }
                                }
                            }
                            ////流程
                            dbContext.SaveChanges();
                        }
                        ////4.日志
                        User_Log log = new User_Log();
                        log.IsrtDate = DateTime.Now;
                        log.IsrtUser = corpInfo.CorpUserGuid.ToString();
                        log.IsrtUserArea = areaCode;
                        log.IsrtUserName = corpInfo.CorpName;
                        baseBll.InsertDetailUserLog("修改企业信息", dbCorpInfo.CorpUserGuid.ToString(), corpInfo.classID.ToString(), "2", log);
                        tran.Commit();
                        result.Message = "修改成功！";
                        result.Result = true;
                        result.ReturnValue = null;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "修改失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 修改企业安全生产许可证
        /// </summary>
        /// <param name="khCorpTable"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult KH_CorpEdit(DTO.Kh_CorpTable khCorpTable, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            Tb_Corp_CompanyInfo_Zbdl dbCorpInfo = dbContext.Corp_CompanyInfos.Where(p => p.CorpUserGuid == khCorpTable.CorpUserGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
            var user = dbContext.T_Sys_Users.Where(u => u.UserGuid == khCorpTable.CorpUserGuid).FirstOrDefault();
            string corpId = khCorpTable.CorpUserGuid.ToString();

            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);

            Kh_CorpTable_Zbdlry khcorp = dbContext.SecurityInfo.Where(p => p.CorpUserGuid == khCorpTable.CorpUserGuid).FirstOrDefault();
            OperationResult checkReuslt = new OperationResult();
            checkReuslt.Result = true;
            ////验证安全生产许可证必填
            if (khCorpTable == null)
            {
                checkReuslt.Message = "安全生产许可证信息不完善，请检查";
                checkReuslt.Result = false;
            }
            else if (string.IsNullOrEmpty(khCorpTable.SafeLicenceNo))
            {
                checkReuslt.Message = "安全生产许可证编号不能为空，请检查";
                checkReuslt.Result = false;
            }
            else if (khCorpTable.LicenceBeginDate == null)
            {
                checkReuslt.Message = "安全生产许可证获取时间不能为空，请检查";
                checkReuslt.Result = false;
            }
            else if (khCorpTable.LicenceEndDate == null)
            {
                checkReuslt.Message = "安全生产许可证有效期不能为空，请检查";
                checkReuslt.Result = false;
            }
            if (!checkReuslt.Result)
            {
                return checkReuslt;
            }
            //判断当前节点是否可操作
            string khFlowCode = string.Empty;
            if (khcorp != null)
            {
                khFlowCode = khcorp.FlowCode == null ? "" : khcorp.FlowCode;
            }
            var nextNode = new BasicBLL().GetNextFlowCode(user.RoleID.ToString(), "", areaCode, khcorp.ClassID.ToString(), khFlowCode, FlowCommon.OptType.Edit);
            if (!nextNode.Result)
            {
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        if (dbCorpInfo != null)
                        {
                            int? securitClassid = dbCorpInfo.classID;
                            if (appid == 101) //聊城 4位的是市直，5位的是县区
                            {
                                securitClassid = securitClassid >= 10000 ? 2602 : 2601;
                            }
                            khCorpTable.ClassID = securitClassid;

                            ////判断企业在注册地是否审核通过，审核通过不允许修改基本信息和安全生产许可证
                            if (khcorp == null || khcorp.FlowCode == null || !khcorp.FlowCode.StartsWith("1"))
                            {
                                Kh_CorpTable_Zbdlry khCorpTable_E = new Kh_CorpTable_Zbdlry();
                                EntityHelper.ConvertEntity2OtherEntity(khCorpTable, khCorpTable_E);
                                if (khcorp != null)
                                {
                                    EntityHelper.ConvertEntity2Entity<Kh_CorpTable_Zbdlry>(khCorpTable_E, khcorp);
                                }
                                else
                                {
                                    khCorpTable_E.FlowCode = "0";
                                    dbContext.SecurityInfo.Add(khCorpTable_E);
                                }
                            }
                            dbContext.SaveChanges();
                        }
                        ////4.日志
                        User_Log log = new User_Log();
                        log.IsrtDate = DateTime.Now;
                        log.IsrtUser = dbCorpInfo.CorpUserGuid.ToString();
                        log.IsrtUserArea = areaCode;
                        log.IsrtUserName = dbCorpInfo.CorpName;
                        baseBll.InsertDetailUserLog("修改安全生产许可证", khCorpTable.CorpUserGuid.ToString(), dbCorpInfo.classID.ToString(), "2", log);
                        tran.Commit();
                        result.Message = "修改成功！";
                        result.Result = true;
                        result.ReturnValue = null;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "修改失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }

            return result;
        }
        #endregion

        #region 添加企业资质
        /// <summary>
        /// 企业资质添加
        /// </summary>
        /// <param name="corpUserGuid">corpUserGuid</param>
        /// <param name="qualities">资质列表，列表中只有一条记录</param>
        /// <param name="isReturnModel"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityAdd(string corpUserGuid
            , IList<DTO.tb_Corp_Quality> qualities
            , bool isReturnModel
            , string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            IList<tb_Corp_Quality_Zbdlry> returnQuality = new List<tb_Corp_Quality_Zbdlry>();
            if (!CheckCorpQualityInfo(corpUserGuid, qualities, out result))
            {
                result.Message = "添加失败：" + result.Message;
                return result;
            }
            Guid userGuid = Guid.Empty;
            Guid.TryParse(corpUserGuid, out userGuid);
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == userGuid).FirstOrDefault();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        ////1.添加tb_Corp_Quality
                        foreach (var item in qualities)
                        {
                            if (item != null)
                            {
                                item.IsDel = false;
                                if (item.QualityGuid == null || item.QualityGuid == Guid.Empty)
                                {
                                    item.QualityGuid = Guid.NewGuid();
                                }
                                item.CorpUserGuid = Guid.Parse(corpUserGuid);
                                tb_Corp_Quality_Zbdlry corpQua_E = new tb_Corp_Quality_Zbdlry();
                                ////用入参DTO为Entity赋值
                                EntityHelper.ConvertEntity2OtherEntity(item, corpQua_E);
                                corpQua_E = dbContext.Corp_CompanyQualities.Add(corpQua_E);
                                ////循环添加返回值
                                returnQuality.Add(corpQua_E);
                                ////3.流程
                                //InsertFlowCode(dbCorpQua.QualityGuid.ToString(), 8030);
                                ////4.日志
                                User_Log log = new User_Log();
                                log.IsrtDate = DateTime.Now;
                                log.IsrtUser = corpUserGuid;
                                log.IsrtUserArea = areaCode;
                                log.IsrtUserName = corp.CorpName;
                                baseBll.InsertDetailUserLog("添加企业资质信息", corpQua_E.QualityGuid.ToString(), corp.classID.ToString() + "02", "1", log);
                            }
                        }
                        dbContext.SaveChanges();
                        tran.Commit();
                        result.Message = "添加成功！";
                        result.Result = true;
                        result.ReturnValue = null;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "添加失败：：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }

            return result;
        }
        #endregion

        #region 修改企业资质
        public override DTO.OperationResult CorpQualityEdit(DTO.tb_Corp_Quality quality, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                List<tb_Corp_Quality> list = new List<tb_Corp_Quality>();
                list.Add(quality);
                if (!CheckCorpQualityInfo(quality.CorpUserGuid.ToString(), list, out result))
                {
                    result.Message = "修改失败：" + result.Message;
                    return result;
                }
                try
                {
                    if (quality.IsDel == null)
                    {
                        quality.IsDel = false;
                    }
                    ////1.修改tb_Corp_Quality
                    ////查询数据库
                    tb_Corp_Quality_Zbdlry dbCorpQuality = dbContext.Corp_CompanyQualities.Where(p => p.QualityGuid == quality.QualityGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == dbCorpQuality.CorpUserGuid).FirstOrDefault();
                    ////修改赋值
                    if (dbCorpQuality != null)
                    {
                        tb_Corp_Quality_Zbdlry tbCorpQuality_E = new tb_Corp_Quality_Zbdlry();
                        ////用入参DTO为Entity赋值
                        EntityHelper.ConvertEntity2OtherEntity(quality, tbCorpQuality_E);
                        EntityHelper.ConvertEntity2Entity<tb_Corp_Quality_Zbdlry>(tbCorpQuality_E, dbCorpQuality);
                    }
                    dbContext.SaveChanges();
                    ////2.日志
                    User_Log log = new User_Log();
                    log.IsrtDate = DateTime.Now;
                    log.IsrtUser = corp.CorpUserGuid.ToString();
                    log.IsrtUserArea = areaCode;
                    log.IsrtUserName = corp.CorpName;
                    baseBll.InsertDetailUserLog("修改企业资质信息", dbCorpQuality.QualityGuid.ToString(), corp.classID.ToString() + "02", "2", log);
                    result.Message = "修改成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }

            }

            return result;
        }
        #endregion

        #region 删除企业资质
        /// <summary>
        /// 支持批量删除
        /// </summary>
        /// <param name="qualityGuid">删除资质Guid的集合</param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpQualityDel(string qualityGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            List<Guid> qualityGuids = new List<Guid>();
            foreach (string guid in qualityGuid.Split(','))
            {
                Guid qg = Guid.Empty;
                if (!string.IsNullOrEmpty(guid) && Guid.TryParse(guid, out qg))
                {
                    qualityGuids.Add(qg);
                }
            }
            var dbCorpQualities = dbContext.Corp_CompanyQualities.Where(p => qualityGuids.Contains(p.QualityGuid) && (p.IsDel != true || p.IsDel == null)).ToList();
            if (dbCorpQualities == null || dbCorpQualities.Count <= 0)
            {
                result.Message = "删除失败,未检测到企业资质！";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            Tb_Corp_CompanyInfo_Zbdl corp = new Tb_Corp_CompanyInfo_Zbdl();
            Guid corpUserGuid = dbCorpQualities[0].CorpUserGuid ?? Guid.Empty;
            corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpUserGuid).FirstOrDefault();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        ////1.修改tb_Corp_Quality
                        if (dbCorpQualities != null && dbCorpQualities.Count > 0)
                        {
                            foreach (var q in dbCorpQualities)
                            {

                                q.IsDel = true;
                            }
                        }
                        dbContext.SaveChanges();
                        ////2.日志
                        User_Log log = new User_Log();
                        log.IsrtDate = DateTime.Now;
                        log.IsrtUser = corp.CorpUserGuid.ToString();
                        log.IsrtUserArea = areaCode;
                        log.IsrtUserName = corp.CorpName;
                        baseBll.InsertDetailUserLog("删除企业资质信息", string.Join(",", qualityGuids.ToArray()), corp.classID.ToString() + "02", "3", log);
                        tran.Commit();
                        result.Message = "删除成功！";
                        result.Result = true;
                        result.ReturnValue = null;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "删除失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }

            return result;
        }
        #endregion

        #region 企业信息上报
        public override DTO.OperationResult CorpPost(string corpUserGuid
            , bool isPostEmp
            , bool isPostQuality
            , string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            var checkResult = CheckPost(corpUserGuid, areaCode);
            if (!checkResult.Result)
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = checkResult.Message;
                return result;
            }
            cGuid = Guid.Parse(corpUserGuid);
            ////企业注册信息上报
            Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            string userguid = corpinfo != null ? corpinfo.CorpUserGuid.ToString() : "";
            ////根据地区获取企业当前状态
            Tb_FlowCode_Zbdl flow = null;
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
            {
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == userguid && f.AreaCode.StartsWith(preArea) &&
                    f.CodeType == corpinfo.classID && f.IsDel == false && f.AppID == appid).FirstOrDefault();
            }
            else
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == userguid && f.AreaCode.StartsWith(preArea) && f.CodeType == corpinfo.classID && f.IsDel == false).FirstOrDefault();

            ////日志初始化
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = corpinfo.CorpUserGuid.ToString();
            log.IsrtUserName = corpinfo.CorpName;
            log.IsrtUserArea = areaCode;
            ////获取企业角色Id
            var corpuser = dbContext.T_Sys_Users.Where(o => o.UserGuid == cGuid).FirstOrDefault();
            string roleId = string.Empty;
            if (corpuser != null)
            {
                roleId = corpuser.RoleID.ToString();
            }
            if (String.IsNullOrEmpty(roleId))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "企业roleid不正确！";
                return result;
            }
            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(roleId, "", areaCode, corpinfo.classID.ToString(), flow == null ? "" : flow.FlowCode, Fly.Common.WorkFlow.OptType.Post);
            if (!nextNode.Result)
            {
                //baseBll.InsertDetailUserLog("企业注册信息上报失败:" + nextNode.Message, corpUserGuid, corpinfo.classID.ToString(), "4", log);
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        if (flow != null)
                        {
                            flow.FlowCode = nextNode.NextFlowCode;
                            flow.Description = nextNode.Message;
                            corpinfo.FlowCode = nextNode.NextFlowCode;
                            ////资质状态
                            var qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                            foreach (var quality in qualities)
                            {
                                quality.FlowCode = nextNode.NextFlowCode;
                            }
                            ////安全生产许可证 
                            var securities = dbContext.SecurityInfo.Where(s => s.CorpUserGuid == cGuid).ToList();
                            foreach (var security in securities)
                            {
                                security.FlowCode = nextNode.NextFlowCode;
                            }
                            dbContext.SaveChanges();
                            ////日志
                            baseBll.InsertDetailUserLog("企业注册信息上报成功", corpUserGuid, corpinfo.classID.ToString(), "4", log);
                            tran.Commit();
                            result.Message = "企业注册信息上报成功！";
                            result.Result = true;
                            result.ReturnValue = null;
                        }
                        else
                        {
                            ////状态未检测到，则添加状态 2014-1-17
                            Tb_FlowCode_Zbdl newFlow = new Tb_FlowCode_Zbdl();
                            newFlow.ObjectId = corpUserGuid;
                            newFlow.FlowCode = nextNode.NextFlowCode;
                            newFlow.AreaCode = areaCode;
                            newFlow.IsDel = false;
                            newFlow.UpdateTime = DateTime.Now;
                            newFlow.CodeType = corpinfo.classID;
                            newFlow.AppID = appid;
                            newFlow.Description = nextNode.Message;
                            dbContext.FlowCodes.Add(newFlow);
                            corpinfo.FlowCode = nextNode.NextFlowCode; ;
                            ////资质状态
                            var qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                            foreach (var quality in qualities)
                            {
                                quality.FlowCode = nextNode.NextFlowCode;
                            }
                            ////安全生产许可证
                            var securities = dbContext.SecurityInfo.Where(s => s.CorpUserGuid == cGuid).ToList();
                            foreach (var security in securities)
                            {
                                security.FlowCode = nextNode.NextFlowCode;
                            }
                            dbContext.SaveChanges();
                            ////日志
                            baseBll.InsertDetailUserLog("企业注册信息上报成功", corpUserGuid, corpinfo.classID.ToString(), "4", log);
                            tran.Commit();
                            result.Message = "企业注册信息上报成功！";
                            result.Result = true;
                            result.ReturnValue = null;
                        }

                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "企业注册信息上报失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 安全生产许可证信息上报
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="isPostEmp"></param>
        /// <param name="isPostQuality"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult KH_CorpPost(string corpUserGuid
            , bool isPostEmp
            , bool isPostQuality
            , string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            cGuid = Guid.Parse(corpUserGuid);

            Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            string userguid = corpinfo != null ? corpinfo.CorpUserGuid.ToString() : "";
            Kh_CorpTable_Zbdlry securityInfo = dbContext.SecurityInfo.Where(f => f.CorpUserGuid == cGuid).FirstOrDefault();

            ////日志初始化
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = corpinfo.CorpUserGuid.ToString();
            log.IsrtUserName = corpinfo.CorpName;
            log.IsrtUserArea = areaCode;
            ////获取企业角色Id
            var corpuser = dbContext.T_Sys_Users.Where(o => o.UserGuid == cGuid).FirstOrDefault();
            string roleId = string.Empty;
            if (corpuser != null)
            {
                roleId = corpuser.RoleID.ToString();
            }
            if (String.IsNullOrEmpty(roleId))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "企业roleid不正确！";
                return result;
            }
            string securityFlowCode = string.Empty;
            if (securityInfo != null)
            {
                securityFlowCode = securityInfo.FlowCode == null ? "" : securityInfo.FlowCode;
            }
            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(roleId, "", areaCode, securityInfo.ClassID.ToString(), securityFlowCode, Fly.Common.WorkFlow.OptType.Post);
            if (!nextNode.Result)
            {
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {
                        if (securityInfo != null)
                        {
                            securityInfo.FlowCode = nextNode.NextFlowCode;
                            dbContext.SaveChanges();

                            ////日志
                            baseBll.InsertDetailUserLog("安全生产许可证信息上报成功", corpUserGuid, corpinfo.classID.ToString(), "4", log);
                            tran.Commit();
                            result.Message = "安全生产许可证信息上报成功！";
                            result.Result = true;
                            result.ReturnValue = null;
                        }

                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "安全生产许可证信息上报失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                }
            }
            return result;
        }

        #endregion

        public override OperationResult CorpCancelPost(string corpUserGuid, string cancelReason, string areacode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (Guid.TryParse(corpUserGuid, out cGuid))
            {
                var corpuser = dbContext.T_Sys_Users.Where(o => o.UserGuid == cGuid).FirstOrDefault();
                Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();

                if (corpuser != null && corpinfo != null)
                {
                    string preArea = string.IsNullOrEmpty(areacode) ? "" : (areacode.Length > 2 ? areacode.Substring(0, 2) : areacode);
                    int appid = 0;
                    int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                    Tb_FlowCode_Zbdl flow = null;
                    if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
                    {
                        flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.AreaCode.StartsWith(preArea) &&
                            f.CodeType == corpinfo.classID && f.IsDel == false && f.AppID == appid).FirstOrDefault();
                    }
                    else
                        flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.AreaCode.StartsWith(preArea) && f.CodeType == corpinfo.classID && f.IsDel == false).FirstOrDefault();

                    if (flow == null)
                    {
                        result.Result = false;
                        result.Message = "企业未在此地区备案！";
                    }
                    else
                    {
                        var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(
                       corpuser.RoleID.ToString(),
                       "",
                       areacode,
                       corpinfo.classID.ToString(),
                        flow.FlowCode,
                       Fly.Common.WorkFlow.OptType.CancelPost);
                        if (!nextNode.Result)
                        {
                            result.Result = false;
                            result.Message = nextNode.Message;
                        }
                        else
                        {
                            ////日志初始化
                            User_Log log = new User_Log();
                            log.IsrtDate = DateTime.Now;
                            log.IsrtUser = corpinfo.CorpUserGuid.ToString();
                            log.IsrtUserName = corpinfo.CorpName;
                            log.IsrtUserArea = areacode;
                            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                            {
                                con.Open();
                                using (DbTransaction tran = con.BeginTransaction())
                                {
                                    try
                                    {
                                        flow.FlowCode = nextNode.NextFlowCode;
                                        flow.AppID = appid;
                                        flow.Description = nextNode.Message;
                                        corpinfo.FlowCode = nextNode.NextFlowCode;
                                        dbContext.SaveChanges();
                                        baseBll.InsertDetailUserLog("企业取消上报信息，原因：" + cancelReason, corpUserGuid, corpinfo.classID.ToString(), "8", log);
                                        tran.Commit();
                                        result.Message = "企业取消上报成功！";
                                        result.Result = true;
                                        result.ReturnValue = null;
                                    }
                                    catch (Exception ex)
                                    {
                                        tran.Rollback();
                                        SysLogManager.Log(new Sys_Log()
                                        {
                                            ErrorMessage = ex.Message,
                                            LogDate = DateTime.Now
                                        });
                                        result.Message = "企业取消上报失败：" + ex.Message;
                                        result.Result = false;
                                        result.ReturnValue = null;
                                    }
                                }
                            }
                        }
                    }

                }
                else
                {
                    result.Result = false;
                    result.Message = "用户不存在！";
                }

            }
            else
            {
                result.Result = false;
                result.Message = "用户GUID编号格式不正确！";
            }
            return result;
        }

        #region 主管审核企业信息
        /// <summary>
        /// 主管审核企业信息通过操作,通过、退回通用，根据User_Log中的FunctionId进行区分
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="log">存放操作类型根据操作类型执行相应的操作</param>
        /// <param name="flowCode"></param>
        /// <param name="description"></param>
        /// <param name="isFinal"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpAudit(string corpUserGuid
            , string areaCode
            , User_Log log
            , string flowCode
            , string description
            , bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////市场范围地区
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            Guid cGuid = Guid.Empty;
            Guid.TryParse(corpUserGuid, out cGuid);
            Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            int functionId = -1;
            if (string.IsNullOrEmpty(log.FunctionId) || !int.TryParse(log.FunctionId, out functionId))
            {
                result.Message = "审核企业信息失败：操作类型错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            Fly.Common.WorkFlow.OptType opt = (Fly.Common.WorkFlow.OptType)functionId;
            string optTitle = GetOptTitle(opt);
            if (corpinfo == null)
            {
                result.Message = optTitle + "企业信息失败：未检测到企业信息";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(log.IsrtUserRole))
            {
                result.Message = optTitle + "企业信息失败：审核用户角色Id无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(corpinfo.classID.ToString()))
            {
                result.Message = optTitle + "企业信息失败：被审核企业classid无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            string corpId = corpinfo.CorpUserGuid.ToString();
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            Tb_FlowCode_Zbdl flow = null;
            if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
            {
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && f.CodeType == corpinfo.classID &&
                    f.AreaCode.StartsWith(preArea) && f.IsDel == false && f.AppID == appid).FirstOrDefault();
            }
            else
                flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && f.CodeType == corpinfo.classID && f.AreaCode.StartsWith(preArea) && f.IsDel == false).FirstOrDefault();

            if (flow == null)
            {
                ////状态为非审核状态
                ////日志
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败", corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Message = optTitle + "企业信息失败：企业未上报或状态错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(log.IsrtUserRole, "", areaCode, corpinfo.classID.ToString(), flow.FlowCode, opt);
            if (!nextNode.Result)
            {
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败:" + nextNode.Message, corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////企业状态
                    flow.FlowCode = nextNode.NextFlowCode;
                    if (corpinfo.AreaCode.StartsWith(preArea))
                    {
                        ////企业注册地主管审核
                        corpinfo.FlowCode = nextNode.NextFlowCode;
                        ////资质状态
                        var qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                        foreach (var quality in qualities)
                        {
                            quality.FlowCode = nextNode.NextFlowCode;
                        }
                        ////安全生产许可证
                        var securities = dbContext.SecurityInfo.Where(s => s.CorpUserGuid == cGuid).ToList();
                        foreach (var security in securities)
                        {
                            security.FlowCode = nextNode.NextFlowCode;
                        }
                    }
                    dbContext.SaveChanges();
                    ////日志
                    baseBll.InsertDetailUserLog(optTitle + "企业信息成功！" + log.Content, corpUserGuid, corpinfo.classID.ToString(), log.FunctionId, log);
                    tran.Commit();
                    result.Message = optTitle + "企业信息成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = optTitle + "企业信息失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        public override DTO.OperationResult CorpSafeAudit(string corpUserGuid
            , string areaCode
            , User_Log log
            , string flowCode
            , string description
            , bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////市场范围地区
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            Guid cGuid = Guid.Empty;
            Guid.TryParse(corpUserGuid, out cGuid);
            Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            int functionId = -1;
            if (string.IsNullOrEmpty(log.FunctionId) || !int.TryParse(log.FunctionId, out functionId))
            {
                result.Message = "审核企业安全生产许可证信息失败：操作类型错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            Fly.Common.WorkFlow.OptType opt = (Fly.Common.WorkFlow.OptType)functionId;
            string optTitle = GetOptTitle(opt);
            if (corpinfo == null)
            {
                result.Message = optTitle + "企业安全生产许可证信息失败：未检测到企业信息";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(log.IsrtUserRole))
            {
                result.Message = optTitle + "企业安全生产许可证信息失败：审核用户角色Id无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(corpinfo.classID.ToString()))
            {
                result.Message = optTitle + "企业安全生产许可证信息失败：被审核企业classid无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            string corpId = corpinfo.CorpUserGuid.ToString();
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);

            Kh_CorpTable_Zbdlry securityInfo = dbContext.SecurityInfo.Where(f => f.CorpUserGuid == cGuid).FirstOrDefault();

            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(log.IsrtUserRole, "", areaCode, securityInfo.ClassID.ToString(), securityInfo.FlowCode, opt);
            if (!nextNode.Result)
            {
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    securityInfo.FlowCode = nextNode.NextFlowCode;
                    dbContext.SaveChanges();
                    ////日志
                    baseBll.InsertDetailUserLog(optTitle + "企业安全生产许可证信息成功！" + log.Content, corpUserGuid, corpinfo.classID.ToString(), log.FunctionId, log);
                    tran.Commit();
                    result.Message = optTitle + "企业安全生产许可证信息成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = optTitle + "企业安全生产许可证信息失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 主管审核企业信息退回操作
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override OperationResult CorpAuditBack(string corpUserGuid, string areaCode, User_Log log)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////市场范围地区
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Guid cGuid = Guid.Empty;
                    Guid.TryParse(corpUserGuid, out cGuid);
                    if (cGuid == Guid.Empty)
                    {
                        result.Result = false;
                        result.Message = "企业唯一标识错误";
                        return result;
                    }
                    Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
                    if (corpinfo != null)
                    {
                        Tb_FlowCode_Zbdl flow = null;
                        if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
                        {
                            flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpinfo.classID &&
                                f.AreaCode.StartsWith(preArea) && f.IsDel == false && f.AppID == appid).FirstOrDefault();
                        }
                        else
                            flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpinfo.classID && f.AreaCode.StartsWith(preArea) && f.IsDel == false).FirstOrDefault();

                        ////流程组件获取下一个流程，判断是否能够继续操作，后期补充
                        var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(log.IsrtUserRole, "", areaCode, corpinfo.classID.ToString(), flow == null ? "" : flow.FlowCode, Fly.Common.WorkFlow.OptType.Reject);
                        if (!nextNode.Result)
                        {
                            baseBll.InsertDetailUserLog("企业注册信息退回失败：" + nextNode.Message, corpUserGuid, corpinfo.classID.ToString(), "6", log);
                            result.Result = false;
                            result.Message = nextNode.Message;
                            return result;
                        }
                        ////企业状态
                        flow.FlowCode = nextNode.NextFlowCode;
                        if (corpinfo.AreaCode.StartsWith(preArea))
                        {
                            ////企业注册地主管审核
                            corpinfo.FlowCode = nextNode.NextFlowCode;
                            ////资质状态
                            var qualities = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == cGuid).ToList();
                            foreach (var quality in qualities)
                            {
                                quality.FlowCode = nextNode.NextFlowCode;
                            }
                            ////安全生产许可证
                            var securities = dbContext.SecurityInfo.Where(s => s.CorpUserGuid == cGuid).ToList();
                            foreach (var security in securities)
                            {
                                security.FlowCode = nextNode.NextFlowCode;
                            }
                        }
                        dbContext.SaveChanges();
                        ////日志
                        baseBll.InsertDetailUserLog("退回企业信息成功", corpUserGuid, corpinfo.classID.ToString(), "6", log);
                        tran.Commit();
                        result.Message = "退回企业信息成功！";
                        result.Result = true;
                        result.ReturnValue = null;
                    }
                    else
                    {
                        result.Message = "退回企业信息失败！未检测到企业信息";
                        result.Result = false;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "退回企业信息失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }
        #endregion

        #region 查询企业列表
        public override IList<DTO.Tb_Corp_CompanyInfo> GetCompaniesInfo(string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var condition = JsonConvert.DeserializeObject<IList<QueryCompanyInfoCondition>>(conditions);
            var query = from c in dbContext.Corp_CompanyInfos
                        join u in dbContext.T_Sys_Users on new { CorpUserGuid = c.CorpUserGuid } equals new { CorpUserGuid = u.UserGuid }
                        select c;
            query = query.BuildCondition<Tb_Corp_CompanyInfo_Zbdl>(condition);
            var corps = query.ToList();
            var dtolist = new List<DTO.Tb_Corp_CompanyInfo>();
            foreach (var item in corps)
            {
                DTO.Tb_Corp_CompanyInfo corpInfo_D = new DTO.Tb_Corp_CompanyInfo();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpInfo_D);
                dtolist.Add(corpInfo_D);
            }
            return dtolist;
        }
        public override int GetCompanyCount(IList<QueryCompanyInfoCondition> queryCondition, string areaCondition)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == areaCondition
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            return query.Count();
        }

        public override IList<CompanyInfo> GetCompanyInfo(IList<QueryCompanyInfoCondition> queryCondition, int pageSize, int pageNum, string areaCondition)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;

            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == areaCondition
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            AppID = company.AppID
                            #endregion
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            var result = new List<DTO.CompanyInfo>();
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }
            foreach (var item in result)
            {
                item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                    areaCondition,
                    item.classID.ToString(),
                    item.FlowCode);
            }
            return result;
        }
        #endregion

        #region 查询企业信息
        public override DTO.Tb_Corp_CompanyInfo GetCompanyInfo(string conditions, string areaCode)
        {
            var condition = JsonConvert.DeserializeObject<IList<QueryCompanyInfoCondition>>(conditions);
            var query = from c in dbContext.Corp_CompanyInfos
                        select c;
            query = query.BuildCondition<Tb_Corp_CompanyInfo_Zbdl>(condition);
            var corp = query.FirstOrDefault();
            DTO.Tb_Corp_CompanyInfo corpInfo_D = new DTO.Tb_Corp_CompanyInfo();
            ////用Entity为入参DTO赋值
            EntityHelper.ConvertEntity2OtherEntity(corp, corpInfo_D);
            return corpInfo_D;
        }

        public override CompanyInfo GetCompanyBisicInfo(IList<QueryCompanyInfoCondition> queryCondition, string areaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == areaCode
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate

                            #endregion
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            var corp = query.FirstOrDefault();
            if (corp != null)
            {
                corp.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                        areaCode,
                        corp.classID.ToString(),
                        corp.FlowCode);
            }
            return corp;
        }
        #endregion

        #region 查询企业资质
        /// <summary>
        /// 查询企业资质,列表和单条资质通用方法，根据条件参数返回相应的结果
        /// </summary>
        /// <param name="corpUserGuid">corpUserGuid</param>
        /// <param name="conditions">条件</param>
        /// <param name="areaCode">市场范围地区</param>
        /// <returns></returns>
        public override IList<DTO.tb_Corp_Quality> GetCompanyQualities(string corpUserGuid, string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var condition = JsonConvert.DeserializeObject<IList<QueryCorpQualityInfoCondition>>(conditions);
            Guid guid = Guid.Empty;
            int CorpID = 0;

            var dtolist = new List<DTO.tb_Corp_Quality>();

            if (Guid.TryParse(corpUserGuid, out guid) || Int32.TryParse(corpUserGuid, out CorpID))
            {
                if (Guid.TryParse(corpUserGuid, out guid))
                {
                    var query = from t in dbContext.Corp_CompanyQualities
                                where t.CorpUserGuid == guid && (t.IsDel == null || t.IsDel == false)
                                select t;
                    query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(condition).OrderByDescending(q => q.IsMain);
                    var list = query.ToList();
                    foreach (var item in list)
                    {
                        DTO.tb_Corp_Quality corpQuality_D = new DTO.tb_Corp_Quality();
                        ////用Entity为入参DTO赋值
                        EntityHelper.ConvertEntity2OtherEntity(item, corpQuality_D);
                        dtolist.Add(corpQuality_D);
                    }

                }
                else if (Int32.TryParse(corpUserGuid, out CorpID))
                {
                    var query = from t in dbContext.Corp_CompanyQualities
                                join c in dbContext.Corp_CompanyInfos
                                on t.CorpUserGuid equals c.CorpUserGuid
                                where c.ID == CorpID && (t.IsDel == null || t.IsDel == false)
                                select t;
                    query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(condition).OrderByDescending(q => q.IsMain);
                    var list = query.ToList();
                    foreach (var item in list)
                    {
                        DTO.tb_Corp_Quality corpQuality_D = new DTO.tb_Corp_Quality();
                        ////用Entity为入参DTO赋值
                        EntityHelper.ConvertEntity2OtherEntity(item, corpQuality_D);
                        dtolist.Add(corpQuality_D);
                    }
                }
            }

            return dtolist;
        }


        public override IList<DTO.tb_Corp_Quality> GetCompanyQualities1(string corpUserGuid, string conditions, string areaCode)
        {
            ////调用DAL中的方法
            var condition = JsonConvert.DeserializeObject<QueryCorpQualityInfoCondition1>(conditions);
            Guid guid = Guid.Empty;
            Guid.TryParse(corpUserGuid, out guid);
            if (guid == Guid.Empty)
            {
                return null;
            }
            var query = from t in dbContext.Corp_CompanyQualities
                        where t.CorpUserGuid == guid && (t.IsDel == null || t.IsDel == false)
                        select t;
            if (condition != null)
            {
                if (condition.IsMain != null)
                {
                    query = query.Where(q => q.IsMain == condition.IsMain);
                }
            }

            //query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(condition).OrderByDescending(q => q.IsMain);
            var list = query.OrderByDescending(q => q.IsMain).ToList();
            var dtolist = new List<DTO.tb_Corp_Quality>();
            foreach (var item in list)
            {
                DTO.tb_Corp_Quality corpQuality_D = new DTO.tb_Corp_Quality();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, corpQuality_D);
                dtolist.Add(corpQuality_D);
            }
            return dtolist;
        }

        public override IList<CorpQuality> GetCorpQualityInfo(IList<QueryCorpQualityInfoCondition> queryCondition, int pageSize, int pageNum, string areaCondition)
        {
            var query = from q in dbContext.Corp_CompanyQualities
                        where q.IsDel == null || q.IsDel == false
                        select q;
            query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(queryCondition);
            IList<tb_Corp_Quality_Zbdlry> qualitylist = null;
            if (pageSize == 0)
            {
                qualitylist = query.ToList();
            }
            else
            {
                qualitylist = query.Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            var dtoList = new List<CorpQuality>();
            foreach (var item in qualitylist)
            {
                CorpQuality quality_D = new CorpQuality();
                EntityHelper.ConvertEntity2OtherEntity(item, quality_D);
                dtoList.Add(quality_D);
            }
            return dtoList;
        }

        public override int GetCorpQualityCount(IList<QueryCorpQualityInfoCondition> queryCondition, string areaCondition)
        {
            var query = from q in dbContext.Corp_CompanyQualities
                        where q.IsDel == null || q.IsDel == false
                        select q;
            query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(queryCondition);
            return query.Count();
        }
        #endregion

        #region 查询安全生产许可证
        public override string GetCorpSecurity(string corpUserGuid, string areaCode)
        {
            Guid userGuid = Guid.Empty;
            Kh_CorpTable_Zbdlry security = null;
            if (Guid.TryParse(corpUserGuid, out userGuid))
            {
                try
                {
                    security = dbContext.SecurityInfo.FirstOrDefault(s => s.CorpUserGuid == userGuid);
                }
                catch
                {
                    security = null;
                }
            }
            DTO.Kh_CorpTable khCorp = new Kh_CorpTable();
            EntityHelper.ConvertEntity2OtherEntity(security, khCorp);
            return JsonConvert.SerializeObject(khCorp);
        }

        /// <summary>
        /// 查询安全生产许可证列表
        /// </summary>
        /// <param name="queryCondition"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNum"></param>
        /// <returns></returns>
        public override IList<DTO.Kh_CorpTable> GetCorpSecurityList(string queryCondition, int pageSize, int pageNum, string areaCode, out int count)
        {
            IList<DTO.QueryPortalCompanyInfoCondition> queryConditionList = JsonConvert.DeserializeObject<IList<DTO.QueryPortalCompanyInfoCondition>>(queryCondition);

            var query = from security in dbContext.SecurityInfo
                        where security.AreaCode.StartsWith(areaCode)
                        select new Kh_CorpTable
                        {
                            ID = security.ID,
                            CorpUserGuid = security.CorpUserGuid,
                            DogID = security.DogID,
                            CorpName = security.CorpName,
                            AreaCode = security.AreaCode,
                            AverageMember = security.AverageMember,
                            SafeLicenceNo = security.SafeLicenceNo,
                            GetLicenceDate = security.GetLicenceDate,
                            LicenceBeginDate = security.LicenceBeginDate,
                            LicenceEndDate = security.LicenceEndDate,
                            LicenceDept = security.LicenceDept,
                            frName = security.frName,
                            frTel = security.frTel,
                            frMobile = security.frMobile,
                            managerName = security.managerName,
                            managerTel = security.managerTel,
                            managerMobile = security.managerMobile,
                            ckName = security.ckName,
                            ckTel = security.ckTel,
                            ckMobile = security.ckMobile,
                            FlowCode = security.FlowCode,
                            AqManagerOrganization = security.AqManagerOrganization,
                            ClassID = security.ClassID
                        };

            if (queryConditionList != null && queryConditionList.Count > 0)
            {
                query = query.BuildCondition<DTO.Kh_CorpTable>(queryConditionList);
            }

            var result = new List<DTO.Kh_CorpTable>();

            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }

            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                        areaCode,
                        item.ClassID.ToString(),
                        item.FlowCode);
                }
                catch
                {
                }
            }

            count = query.Count();
            return result;
        }

        #endregion

        #region 查询操作日志
        /// <summary>
        /// 查询操作日志
        /// </summary>
        /// <param name="objectId">对象唯一标识</param>
        /// <param name="codeType">业务标识</param>
        /// <param name="areaCode">市场范围地区</param>
        /// <returns></returns>
        public override IList<User_Log> GetUserLog(string objectId, string codeType, string areaCode)
        {
            ////调用DAL中的方法
            var query = from log in dbContext.UserLogs.Where(l => l.IsrtUserArea.StartsWith(areaCode) && l.ObjectId == objectId)
                        select log;
            if (!string.IsNullOrEmpty(codeType))
            {
                query = from log in dbContext.UserLogs.Where(l => l.IsrtUserArea.StartsWith(areaCode) && l.ObjectId == objectId && l.FunctionId == codeType)
                        select log;
            }
            query = query.OrderByDescending(l => l.IsrtDate);
            var list = query.ToList();

            return list;
        }
        #endregion

        #region 查询企业市场范围信息
        /// <summary>
        /// 修改：市场范围排除外省的情况  毛凯 2013-9-12
        /// 逻辑修改：毛凯 2014-01-06
        /// 市场范围以Tb_FlowCode为准，即使分支机构表Tb_Corp_Embranchment中无记录，Tb_FlowCode中存在，则认为在该地区已存在市场
        /// </summary>
        /// <param name="corpInfo"></param>
        /// <returns></returns>
        public override List<Tb_Corp_Embranchment> GetCorpEmbranchments(Tb_Corp_CompanyInfo corpInfo)
        {
            string strCorpUserGuid = corpInfo.CorpUserGuid.ToString();
            var companyInfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpInfo.CorpUserGuid).FirstOrDefault();
            if (companyInfo == null)
            {
                return null;
            }
            var query = from em in dbContext.CorpEmbranchment
                        where em.CorpUserGuid == corpInfo.CorpUserGuid && !em.AreaCode.StartsWith(OutProvinceAreaCode)
                        select em;
            var list = query.ToList();

            List<Tb_FlowCode_Zbdl> flowCodes = null;

            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                int appid = 0;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                flowCodes = dbContext.FlowCodes.Where(f => f.ObjectId == strCorpUserGuid && f.CodeType == companyInfo.classID
                    && (f.IsDel == null || f.IsDel == false) && f.AppID == appid).ToList();
            }
            else
                flowCodes = dbContext.FlowCodes.Where(f => f.ObjectId == strCorpUserGuid && f.CodeType == companyInfo.classID && (f.IsDel == null || f.IsDel == false)).ToList();

            foreach (var flow in flowCodes)
            {
                var areaCode = flow.AreaCode;
                var flowCode = flow.FlowCode;
                var curMarket = list.Where(l => l.AreaCode.StartsWith(areaCode)).FirstOrDefault();
                if (curMarket == null)
                {
                    list.Add(new Tb_Corp_Embranchment_Zbdl()
                    {
                        AreaCode = areaCode,
                        CorpUserGuid = corpInfo.CorpUserGuid
                    });
                }
            }
            List<Tb_Corp_Embranchment> dtoList = new List<Tb_Corp_Embranchment>();
            foreach (var item in list)
            {
                Tb_Corp_Embranchment dtoEmBranchment = new Tb_Corp_Embranchment();
                EntityHelper.ConvertEntity2OtherEntity(item, dtoEmBranchment);
                dtoList.Add(dtoEmBranchment);
            }
            return dtoList;
        }
        #endregion

        #region 查询企业在当前市场范围审核状态
        public override Tb_FlowCode GetCorpFlowCode(Tb_Corp_CompanyInfo corpInfo, string areaCode)
        {
            if (corpInfo == null)
            {
                return null;
            }
            areaCode = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;

            var corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpInfo.CorpUserGuid).FirstOrDefault();
            string corpId = corpInfo.CorpUserGuid.ToString();
            var query = from f in dbContext.FlowCodes
                        where f.ObjectId == corpId && f.CodeType == corp.classID && f.AreaCode.StartsWith(areaCode) && (f.IsDel == null || f.IsDel == false)
                        select f;
            Tb_FlowCode_Zbdl flowCode = null;

            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                int appid = 0;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                flowCode = query.Where(r => r.AppID == appid).FirstOrDefault();
            }
            else
                flowCode = query.FirstOrDefault();
            Tb_FlowCode dtoFlowCode = new Tb_FlowCode();
            EntityHelper.ConvertEntity2OtherEntity(flowCode, dtoFlowCode);
            return dtoFlowCode;
        }
        #endregion

        public override string GetCompanyinfoByZbdlDogid(int dogid)
        {
            var qdContext = new QD_Context();
            var qdCorps = qdContext.Corp_CompanyInfos;
            var qdUsers = qdContext.T_Sys_Users;
            var query = from qdUser in qdUsers
                        join qdCorp in qdCorps on qdUser.UserGuid equals qdCorp.CorpUserGuid
                        where qdUser.KeyId == dogid
                        select new
                        {
                            DogId = qdUser.DogID,
                            CorpId = qdCorp.ID,
                            RoleId = qdUser.RoleID,
                            Title = qdCorp.CorpName,
                            Guid = qdUser.UserGuid
                        };
            var result = query.SingleOrDefault();
            return JsonConvert.SerializeObject(result);
        }

        #region 添加分支机构(市场范围)
        public override OperationResult EmbranchAdd(string corpUserGuid, string areaCode)
        {
            OperationResult result = new OperationResult();
            try
            {
                Guid guid = Guid.Empty;

                if (!Guid.TryParse(corpUserGuid, out guid))
                {
                    result.Result = false;
                    result.Message = "企业唯一标识错误";
                    return result;
                }
                var corpInfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == guid).FirstOrDefault();
                var embranch = dbContext.CorpEmbranchment.Where(e => e.CorpUserGuid == guid && e.AreaCode.StartsWith(areaCode) && (e.IsDel == null || e.IsDel == false)).FirstOrDefault();
                if (corpInfo == null)
                {
                    result.Result = false;
                    result.Message = "未检测到企业信息";
                    return result;
                }
                if (embranch != null)
                {
                    result.Result = false;
                    result.Message = "该市场范围已存在";
                    return result;
                }
                Tb_Corp_Embranchment_Zbdl newEmbranch = new Tb_Corp_Embranchment_Zbdl();
                newEmbranch.BranchGid = Guid.NewGuid();
                newEmbranch.CorpUserGuid = guid;
                newEmbranch.AreaCode = areaCode;
                newEmbranch.IsrtDate = DateTime.Now;
                dbContext.CorpEmbranchment.Add(newEmbranch);

                Tb_FlowCode_Zbdl flowCode = null;
                int appid = 0;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);

                string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
                if ("06" == preAreaCode)
                {
                    flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpInfo.classID
                        && f.AreaCode.StartsWith(areaCode) && (f.IsDel == null || f.IsDel == false) && f.AppID == appid).FirstOrDefault();
                }
                else
                    flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpInfo.classID && f.AreaCode.StartsWith(areaCode) && (f.IsDel == null || f.IsDel == false)).FirstOrDefault();
                if (flowCode == null)
                {
                    Tb_FlowCode_Zbdl newEmbranchFlow = new Tb_FlowCode_Zbdl();
                    newEmbranchFlow.ObjectId = corpUserGuid;
                    newEmbranchFlow.FlowCode = "0";
                    newEmbranchFlow.AreaCode = areaCode;
                    newEmbranchFlow.AppID = appid;
                    newEmbranchFlow.IsDel = false;
                    newEmbranchFlow.UpdateTime = DateTime.Now;
                    newEmbranchFlow.CodeType = corpInfo.classID;
                    dbContext.FlowCodes.Add(newEmbranchFlow);
                }
                dbContext.SaveChanges();
                User_Log log = new User_Log();
                log.IsrtDate = DateTime.Now;
                log.IsrtUser = corpUserGuid;
                log.IsrtUserArea = areaCode;
                log.IsrtUserName = corpInfo.CorpName;
                baseBll.InsertDetailUserLog("添加市场范围", corpUserGuid, corpInfo.classID.ToString(), "2", log);
                result.Message = "修改成功！";
                result.Result = true;
                result.ReturnValue = null;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "添加市场范围失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            return result;
        }
        #endregion

        #region 获取企业资质图片
        public override string GetCorpZZImages(IList<QueryCorpQualityInfoCondition> queryCondition, string areaCode)
        {
            var query = from q in dbContext.Corp_CompanyQualities
                        where q.IsDel == null || q.IsDel == false
                        select q;
            query = query.OrderByDescending(q => q.IsMain).ThenBy(q => q.ID);
            query = query.BuildCondition<tb_Corp_Quality_Zbdlry>(queryCondition);
            var qualitys = query.ToList();
            var dtoList = new List<CorpQuality>();
            foreach (var item in qualitys)
            {
                CorpQuality quality_D = new CorpQuality();
                EntityHelper.ConvertEntity2OtherEntity(item, quality_D);
                dtoList.Add(quality_D);
            }
            return JsonConvert.SerializeObject(dtoList);
        }
        #endregion

        #region 企业统计
        public override StatisticsStruct GetStatisticCorps(string areaCode, string flowCodes)
        {
            string code = areaCode.Substring(0, 2);
            StatisticsStruct ssResult = new StatisticsStruct();
            List<StatisticsStruct.StatisticsHeader> headerList = new List<StatisticsStruct.StatisticsHeader>();
            var queryResult = GetStatisticList(code, flowCodes);
            var classIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(new BasicBLL().GetSysStaticSettings("CORPCLASSID", code));
            var areaList = dbContext.AreaSubInfo.Where(a => a.Code == areaCode).OrderBy(a => a.CodeForSort).ToList();
            ////处理统计结果
            StatisticsStruct.StatisticsHeader newHeader = new StatisticsStruct.StatisticsHeader();
            List<StatisticsStruct.StatisticsCell> headerCellList = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell areaCodeThCell = new StatisticsStruct.StatisticsCell();
            areaCodeThCell.Value = "areaCode";
            headerCellList.Add(areaCodeThCell);
            StatisticsStruct.StatisticsCell areaThCell = new StatisticsStruct.StatisticsCell();
            areaThCell.Value = "地区";
            headerCellList.Add(areaThCell);
            foreach (string key in classIds.Keys)
            {
                StatisticsStruct.StatisticsCell newThCell = new StatisticsStruct.StatisticsCell();
                newThCell.Value = classIds[key];
                headerCellList.Add(newThCell);
            }
            newHeader.HeaderCells = headerCellList.ToArray();
            headerList.Add(newHeader);
            ssResult.Header = headerList.ToArray();
            List<StatisticsStruct.StatisticsRow> rowList = new List<StatisticsStruct.StatisticsRow>();
            foreach (var a in areaList)
            {
                var newRow = CreateStatisticRow(a.SortCode, a.Title, queryResult, classIds);
                rowList.Add(newRow);
            }
            ////本地汇总 地区号传两位
            var localRow = CreateStatisticRow(code, "本地", queryResult, classIds);
            rowList.Add(localRow);
            ////外地汇总 两位地区号+99
            var nonLocalRow = CreateStatisticRow(code + "99", "外地", queryResult, classIds);
            rowList.Add(nonLocalRow);
            ////总计 地区号传空
            var totalRow = CreateStatisticRow("", "总计", queryResult, classIds);
            rowList.Add(totalRow);
            ssResult.Data = rowList.ToArray();
            return ssResult;
        }
        #endregion

        #region 校验企业是否可编辑
        /// <summary>
        /// 获取企业下所有地区的审核状态，判断是否可修改
        /// 和分支机构表没有太大关系，正常数据分子机构与审批流程是一一对应
        /// 非正常数据可能没有分子机构表
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override OperationResult CheckCorpEditStatus(string corpUserGuid, string areaCode)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            Guid userGuid = Guid.Empty;
            areaCode = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            if (string.IsNullOrEmpty(corpUserGuid) || !Guid.TryParse(corpUserGuid, out userGuid))
            {
                result.Result = false;
                result.Message = "企业唯一标识错误";
            }
            else
            {
                var corpInfo = dbContext.Corp_CompanyInfos.FirstOrDefault(c => c.CorpUserGuid == userGuid);
                var userInfo = dbContext.T_Sys_Users.FirstOrDefault(u => u.UserGuid == userGuid);
                if (corpInfo == null || userInfo == null)
                {
                    result.Result = false;
                    result.Message = "企业信息错误";
                }
                else
                {
                    List<Tb_FlowCode_Zbdl> flows = null;
                    if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
                    {
                        int appid = 97;
                        int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                        flows = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && (f.IsDel == null || f.IsDel == false)
                            && f.CodeType == corpInfo.classID && f.AppID == appid).ToList();
                    }
                    else
                        flows = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && (f.IsDel == null || f.IsDel == false) && f.CodeType == corpInfo.classID).ToList();

                    foreach (var f in flows)
                    {
                        BasicBLL basicBll = new BasicBLL();
                        var curResult = basicBll.GetNextFlowCode(userInfo.RoleID.ToString(), "", f.AreaCode, corpInfo.classID.ToString(), f.FlowCode, FlowCommon.OptType.Edit);
                        if (!curResult.Result)
                        {
                            result.Result = false;
                            result.Message = curResult.Message;
                            break;
                        }
                    }
                }

            }
            return result;
        }

        /// <summary>
        /// 判断企业安全生产许可证是否可编辑
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override OperationResult CheckSecurityEditStatus(string corpUserGuid, string areaCode)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            Guid userGuid = Guid.Empty;
            areaCode = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            if (string.IsNullOrEmpty(corpUserGuid) || !Guid.TryParse(corpUserGuid, out userGuid))
            {
                result.Result = false;
                result.Message = "企业唯一标识错误";
            }
            else
            {
                Kh_CorpTable_Zbdlry securityInfo = dbContext.SecurityInfo.Where(f => f.CorpUserGuid == userGuid).FirstOrDefault();
                var userInfo = dbContext.T_Sys_Users.FirstOrDefault(u => u.UserGuid == userGuid);
                if (securityInfo == null)
                {
                    //result.Result = false;
                    //result.Message = "企业安全生产许可证信息错误";
                }
                else
                {
                    BasicBLL basicBll = new BasicBLL();
                    string securityArea = securityInfo.AreaCode;
                    securityArea = securityArea.Length > 2 ? securityArea.Substring(0, 2) : securityArea;
                    string flowCode = securityInfo.FlowCode == null ? "0" : securityInfo.FlowCode;

                    var curResult = basicBll.GetNextFlowCode(userInfo.RoleID.ToString(), "", securityArea, securityInfo.ClassID.ToString(), flowCode, FlowCommon.OptType.Edit);
                    if (!curResult.Result)
                    {
                        result.Result = false;
                        result.Message = curResult.Message;
                    }

                }

            }
            return result;
        }
        #endregion

        private bool CheckCorpQualityInfo(string corpUserGuid, IList<DTO.tb_Corp_Quality> qualities, out DTO.OperationResult result)
        {
            result = new OperationResult();
            Guid userGuid = Guid.Empty;
            if (Guid.TryParse(corpUserGuid, out userGuid) && userGuid != Guid.Empty)
            {
                var mainQualitiesCount = qualities.Where(q => q.IsMain == true).Count();
                var qualityGuids = qualities.Select(q => q.QualityGuid).Distinct();
                var existMainQualitiesCount = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == userGuid && q.IsMain == true && !qualityGuids.Contains(q.QualityGuid) && (q.IsDel != true || q.IsDel == null)).Count();
                if (mainQualitiesCount + existMainQualitiesCount > 1)
                {
                    ////主项资质超过一项则提示失败
                    result.Message = "主项资质最多添加一项，您已经拥有主项资质";
                    result.Result = false;
                    result.ReturnValue = null;
                    return false;
                }
                ////验证资质是否已存在，一个企业下某项资质只允许存在一个
                ////验证资质编号是否唯一，所有企业资质编号不能重复
                foreach (var qual in qualities)
                {
                    if ((qual.KindID ?? 0) <= 0)
                    {
                        result.Message = "资质类型不能为空，请选择";
                        result.Result = false;
                        result.ReturnValue = null;
                        return false;
                    }
                    ////有些资质无等级，则不进行等级的检测 2013-11-25 毛凯
                    var code = (qual.KindID ?? -1).ToString();
                    var qualSid = dbContext.Dictionary.Where(q => q.Code == code).Select(q => q.SID).FirstOrDefault();
                    var dicRelation = dbContext.DictionaryRelation;
                    var qualGrade = from relation in dicRelation
                                    join dic in dbContext.Dictionary on relation.ChildID equals dic.SID
                                    where relation.ParentID == qualSid
                                    select dic;
                    var grades = qualGrade.ToList();
                    if (grades != null && grades.Count > 0)
                    {
                        if (string.IsNullOrEmpty(qual.GradeCode))
                        {
                            result.Message = "资质等级不能为空，请选择";
                            result.Result = false;
                            result.ReturnValue = null;
                            return false;
                        }
                    }
                    if (string.IsNullOrEmpty(qual.QualityCode))
                    {
                        result.Message = "资质编号不能为空";
                        result.Result = false;
                        result.ReturnValue = null;
                        return false;
                    }
                    if (!qual.GetDate.HasValue)
                    {
                        result.Message = "资质获取时间不能为空";
                        result.Result = false;
                        result.ReturnValue = null;
                        return false;
                    }
                    //if (!qual.zzzEndDate.HasValue)
                    //{
                    //    result.Message = "资质有效期至不能为空";
                    //    result.Result = false;
                    //    result.ReturnValue = null;
                    //    return false;
                    //}
                    var existKindQualitiesCount = dbContext.Corp_CompanyQualities.Where(q => q.KindID == qual.KindID && !qualityGuids.Contains(q.QualityGuid) && q.CorpUserGuid == userGuid && (q.IsDel != true || q.IsDel == null)).Count();
                    var existQualityCodeCount = dbContext.Corp_CompanyQualities.Where(q => q.QualityCode == qual.QualityCode && !qualityGuids.Contains(q.QualityGuid) && (q.IsDel != true || q.IsDel == null)).Count();
                    if (existKindQualitiesCount > 0)
                    {
                        result.Message = "您已拥有" + qual.DetailName + "资质，不能重复添加";
                        result.Result = false;
                        result.ReturnValue = null;
                        return false;
                    }
                    ////证书编号暂时屏蔽 2013-10-18 by 毛凯
                    //if (existQualityCodeCount > 0)
                    //{
                    //    result.Message = "资质编号" + qual.QualityCode + "已存在，请检查是否正确";
                    //    result.Result = false;
                    //    result.ReturnValue = null;
                    //    return false;
                    //}
                }
            }
            else
            {
                result.Message = "企业信息错误";
                result.Result = false;
                result.ReturnValue = null;
                return false;
            }
            return true;
        }

        private OperationResult CheckCopInfo(DTO.Tb_Corp_CompanyInfo corpInfo, DTO.Kh_CorpTable khCorpTable, DTO.Tb_Corp_Embranchment embranchMent)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            if (corpInfo != null)
            {
                var certificateType = corpInfo.CertificateType;
                var certificateNum = corpInfo.CertificateNumber;
                if (certificateType == 1)
                {
                    ////身份证
                    if (!PersonIDCardValid.CheckIDCard(certificateNum.Trim()))
                    {
                        result.Message = "身份证号不合法！";
                        result.Result = false;
                    }
                }
                ////组织机构代码，同类型企业是否重复
                var companyinfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpInfo.CorpUserGuid).FirstOrDefault();
                var OrginazationCode = corpInfo.OrginazationCode;
                if (string.IsNullOrEmpty(OrginazationCode))
                {
                    result.Message = "组织机构代码不能为空！";
                    result.Result = false;
                }
                else
                {
                    var corpInfoWithSameOrgCode = dbContext.Corp_CompanyInfos.Where(c => c.OrginazationCode == OrginazationCode && c.classID == companyinfo.classID && c.CorpUserGuid != corpInfo.CorpUserGuid).FirstOrDefault();
                    if (corpInfoWithSameOrgCode != null)
                    {
                        result.Message = "组织机构代码已被企业【" + corpInfoWithSameOrgCode.CorpName + "】注册，请检查！";
                        result.Result = false;
                    }
                }
                if (corpInfo.classID == 2501)
                {
                    ////验证安全生产许可证必填
                    if (khCorpTable == null)
                    {
                        result.Message = "安全生产许可证信息不完善，请检查";
                        result.Result = false;
                    }
                    else if (string.IsNullOrEmpty(khCorpTable.SafeLicenceNo))
                    {
                        result.Message = "安全生产许可证编号不能为空，请检查";
                        result.Result = false;
                    }
                    else if (khCorpTable.LicenceBeginDate == null)
                    {
                        result.Message = "安全生产许可证获取时间不能为空，请检查";
                        result.Result = false;
                    }
                    else if (khCorpTable.LicenceEndDate == null)
                    {
                        result.Message = "安全生产许可证有效期不能为空，请检查";
                        result.Result = false;
                    }
                }

            }
            return result;
        }

        private string GetOptTitle(Fly.Common.WorkFlow.OptType opt)
        {
            string title = "";
            switch (opt)
            {
                case FlowCommon.OptType.Add:
                    title = "添加";
                    break;
                case FlowCommon.OptType.Audit:
                    title = "审核";
                    break;
                case FlowCommon.OptType.Delete:
                    title = "删除";
                    break;
                case FlowCommon.OptType.Edit:
                    title = "编辑";
                    break;
                case FlowCommon.OptType.Post:
                    title = "上报";
                    break;
                case FlowCommon.OptType.Reject:
                    title = "退回";
                    break;
                case FlowCommon.OptType.Search:
                    title = "查询";
                    break;
                case FlowCommon.OptType.Unknow:
                    title = "未知操作";
                    break;
                case FlowCommon.OptType.UnlockReject:
                    title = "解锁退回";
                    break;
            }
            return title;
        }

        private OperationResult CheckPost(string strCorpUserGuid, string areaCode)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            Guid corpUserGuid = Guid.Empty;
            if (!Guid.TryParse(strCorpUserGuid, out corpUserGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "corpUserGuid不正确！";
                return result;
            }
            ////验证是否有主项资质
            List<QueryCorpQualityInfoCondition> list = new List<QueryCorpQualityInfoCondition>();
            QueryCorpQualityInfoCondition queryQual = new QueryCorpQualityInfoCondition();
            queryQual.CorpUserGuid = new ParameterValue<Guid>() { O = OptEnum.Equal, V = corpUserGuid };
            queryQual.IsMain = new ParameterValue<bool?>() { O = OptEnum.Equal, V = true };
            list.Add(queryQual);
            var mainQualCount = GetCorpQualityCount(list, areaCode);
            var noQualityClassId = ConfigurationManager.AppSettings["NoQualityClassId"];
            ////无资质企业类型不验证资质情况
            bool notCheckQuality = false;
            if (!string.IsNullOrEmpty(noQualityClassId))
            {
                var corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpUserGuid).FirstOrDefault();
                if (corp != null)
                {
                    notCheckQuality = noQualityClassId.Split(',').Contains(corp.classID.ToString());
                }
            }
            if (mainQualCount < 1 && !notCheckQuality)
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "企业尚未添加主项资质，请添加！";
                return result;
            }
            ////验证管理人员信息是否完善
            //string[] managerTypes = new string[] { "3", "4", "5", "7", "8" };
            string[] managerTypes = new string[] { "3", "4", "5" };//法人为必填项
            foreach (string type in managerTypes)
            {
                var query = from m in dbContext.Emp_Manager
                            where (m.IsDel == null || m.IsDel == false) && m.CorpGuid == corpUserGuid && m.TypeFlag.Contains(type)
                            select m;
                var manager = query.FirstOrDefault();
                if (manager == null)
                {
                    result.Result = false;
                    result.ReturnValue = null;
                    result.Message = "管理人员信息不完善，法人、企业负责人、技术负责人为必填项，请补充！";
                    return result;
                }
            }
            return result;
        }

        private List<StatisticsModel> GetStatisticList(string areaCode, string flowCodes)
        {
            string code = areaCode.Substring(0, 2);
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var query = from corp in dbContext.CompanyInfoFlow
                        join area in dbContext.AreaSubInfo on corp.AreaCode equals area.SortCode
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = corp.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where (corp.IsDel == null || corp.IsDel == false) && (corp.FlowIsDel == null || corp.FlowIsDel == false)
                        && corp.FlowAreaCode.StartsWith(code)
                        && corp.RealFlowCode.Contains("019")
                        group corp by new
                        {
                            corp.AreaCode,
                            corp.classID
                        } into result
                        select new StatisticsModel
                        {
                            AreaCode = result.Key.AreaCode,
                            ClassId = result.Key.classID ?? 0,
                            StatisticsCount = result.Count()
                        };
            if (!string.IsNullOrEmpty(flowCodes))
            {
                var flow = flowCodes.Split('|');
                query = from corp in dbContext.CompanyInfoFlow
                        join area in dbContext.AreaSubInfo on corp.AreaCode equals area.SortCode
                        where (corp.IsDel == null || corp.IsDel == false) && (corp.FlowIsDel == null || corp.FlowIsDel == false)
                        && (corp.FlowAreaCode.StartsWith(code))
                        && flow.Contains(corp.RealFlowCode)
                        group corp by new
                        {
                            corp.AreaCode,
                            corp.classID
                        } into result
                        select new StatisticsModel
                        {
                            AreaCode = result.Key.AreaCode,
                            ClassId = result.Key.classID ?? 0,
                            StatisticsCount = result.Count()
                        };
            }
            var queryResult = query.ToList();
            return queryResult;
        }

        private StatisticsStruct.StatisticsRow CreateStatisticRow(string areaCode, string areaTitle, List<StatisticsModel> list, Dictionary<string, string> dic)
        {
            string code = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cellList = new List<StatisticsStruct.StatisticsCell>();
            cellList.Add(new StatisticsStruct.StatisticsCell() { Value = areaCode });
            cellList.Add(new StatisticsStruct.StatisticsCell() { Value = areaTitle });
            if (string.IsNullOrEmpty(areaCode))
            {
                ////总计
                foreach (var key in dic.Keys)
                {
                    StatisticsStruct.StatisticsCell totalCell = new StatisticsStruct.StatisticsCell();
                    int clsId = int.Parse(key);
                    var Count = (from c in list
                                 where c.ClassId == clsId
                                 select c.StatisticsCount).Sum();
                    totalCell.Value = Count.ToString();
                    cellList.Add(totalCell);
                }
            }
            else if (areaCode == code)
            {
                ////本地汇总
                foreach (var key in dic.Keys)
                {
                    StatisticsStruct.StatisticsCell totalCell = new StatisticsStruct.StatisticsCell();
                    int clsId = int.Parse(key);
                    var Count = (from c in list
                                 where c.AreaCode.StartsWith(code) && c.ClassId == clsId
                                 select c.StatisticsCount).Sum();
                    totalCell.Value = Count.ToString();
                    cellList.Add(totalCell);
                }
            }
            else if (areaCode == code + "99")
            {
                ////外地汇总
                foreach (var key in dic.Keys)
                {
                    StatisticsStruct.StatisticsCell totalCell = new StatisticsStruct.StatisticsCell();
                    int clsId = int.Parse(key);
                    var Count = (from c in list
                                 where !c.AreaCode.StartsWith(code) && c.ClassId == clsId
                                 select c.StatisticsCount).Sum();
                    totalCell.Value = Count.ToString();
                    cellList.Add(totalCell);
                }
            }
            else
            {
                foreach (var key in dic.Keys)
                {
                    StatisticsStruct.StatisticsCell newCell = new StatisticsStruct.StatisticsCell();
                    int clsId = int.Parse(key);
                    var classAreaResult = list.Where(r => r.AreaCode == areaCode && r.ClassId == clsId).FirstOrDefault();
                    if (classAreaResult == null)
                    {
                        newCell.Value = "0";
                    }
                    else
                    {
                        newCell.Value = classAreaResult.StatisticsCount.ToString();
                    }
                    cellList.Add(newCell);
                }

            }
            row.DataCells = cellList.ToArray();
            return row;
        }

        public override List<e_SorcePublish_2006> GetCorpAssessInfo(string corpUserGuid, int bgrade, int bFlag)
        {
            List<e_SorcePublish_2006_Zbdl> e_score = new List<e_SorcePublish_2006_Zbdl>();
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out guid))
            {
                return null;
            }
            var corp = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == guid).FirstOrDefault();
            if (corp != null && corp.dogid != null)
            {
                e_score = dbContext.SorcePublish.Where(e => e.bGrade == bgrade && e.bFlag == bFlag && e.TreeID == corp.dogid).ToList();
            }
            var dtolist = new List<DTO.e_SorcePublish_2006>();
            foreach (var item in e_score)
            {
                DTO.e_SorcePublish_2006 score_D = new DTO.e_SorcePublish_2006();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, score_D);
                dtolist.Add(score_D);
            }
            return dtolist;
        }

        public override StatisCorpPanel GetCorpPanelInfo(StatisCorpPanel corpPanel)
        {
            if (corpPanel != null && corpPanel.ListQuality != null)
            {
                List<CntCorpQuality> ret = new List<CntCorpQuality>();
                foreach (var item in corpPanel.ListQuality)
                {
                    ret = ret.Concat(GetCorpCnt(item, corpPanel.AreaCode, corpPanel.FlowAreaCode)).ToList();
                }
                corpPanel.ListQuality = ret;
            }
            return corpPanel;
        }

        private List<CntCorpQuality> GetCorpCnt(CntCorpQuality item, string areaCode, string flowAreaCode)
        {
            int classid = item.ClassId;
            string strclass = classid.ToString();
            var dics = dbContext.Dictionary;
            var title = dics.Where(o => o.Code == strclass).FirstOrDefault();
            if (title != null)
            {
                item.ClassTitle = title.Name;
            }
            List<QueryPortalCompanyInfoCondition> queryCompanyInfoList = new List<QueryPortalCompanyInfoCondition>();
            QueryPortalCompanyInfoCondition queryCompanyInfoCondition = new QueryPortalCompanyInfoCondition();
            if (!string.IsNullOrEmpty(areaCode))
            {
                if (areaCode == "0201")
                {
                    //List<ParameterValue<string>> paralist = new List<ParameterValue>();
                    queryCompanyInfoCondition.AreaCode = new ParameterValues<string>()
                    {
                        Logic = LogicEnum.Or,
                        Values = new List<ParameterValue<string>>()
                        {
                            new ParameterValue<string>(){ O=OptEnum.StartWith,V="0201"},
                            new ParameterValue<string>(){ O=OptEnum.StartWith,V="0202"},
                            new ParameterValue<string>(){ O=OptEnum.StartWith,V="0203"},
                            new ParameterValue<string>(){ O=OptEnum.StartWith,V="0216"}
                        }
                    };
                }
                else if (areaCode == "9999")
                {
                    queryCompanyInfoCondition.AreaCode = new ParameterValues<string>()
                    {
                        Logic = LogicEnum.And,
                        Values = new List<ParameterValue<string>>()
                        {
                            new ParameterValue<string>(){ O=OptEnum.NotStartWith,V=flowAreaCode},
                        }
                    };
                }
                else
                {
                    queryCompanyInfoCondition.AreaCode = new ParameterValues<string>()
                    {
                        Logic = LogicEnum.And,
                        Values = new List<ParameterValue<string>>()
                        {
                            new ParameterValue<string>(){ O=OptEnum.StartWith,V=areaCode},
                        }
                    };
                }
            }
            queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = classid };
            if (item.KindID != null)
            {
                queryCompanyInfoCondition.KindID = new ParameterValue<int?>() { O = Fly.Common.Linq.OptEnum.Equal, V = item.KindID };
            }
            if (!string.IsNullOrEmpty(item.DetailName))
            {
                queryCompanyInfoCondition.DetailName = new ParameterValue<string>() { O = Fly.Common.Linq.OptEnum.Like, V = item.DetailName };
            }
            //queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = "1," };
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            List<CntCorpQuality> listQual = GetPortalCorpList(queryCompanyInfoList, 0, 0, flowAreaCode).GroupBy(o => o.GradeCode).Select(k => new CntCorpQuality { PID = item.PID, ClassId = item.ClassId, ClassTitle = item.ClassTitle, GradeName = k.Select(o => o.GradeName).FirstOrDefault(), GradeCode = k.Select(o => o.GradeCode).FirstOrDefault(), DetailName = k.Select(o => o.DetailName).FirstOrDefault(), Cnt = k.Count() }).ToList();
            return listQual;
        }

        public override IList<CompanyInfo> GetPortalCorpList(IList<QueryPortalCompanyInfoCondition> queryCondition, int pageSize, int pageNum, string flowAreaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            if (!string.IsNullOrEmpty(flowAreaCode))
            {
                query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == flowAreaCode
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            }
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            if (queryCondition.Where(o => o.classID != null && o.classID.V != null && o.classID.V == 2509).FirstOrDefault() != null)
            {
                query = query.OrderByDescending(o => o.ID);
            }
            else
            {
                query = query
                    .Where(s => !string.IsNullOrEmpty(s.GradeCode) && !string.IsNullOrEmpty(s.GradeName))
                    .OrderByDescending(o => o.DetailName != null && o.DetailName.Contains("综合"))
                    .ThenByDescending(o => o.DetailName != null && o.DetailName.Contains("房屋建筑"))
                    .ThenByDescending(o => "32150".IndexOf(o.GradeCode))//GradeCode按照0,5,1,2,3倒序排列
                    .ThenByDescending(o => o.bISO14000);
            }
            if (flowAreaCode != "06")
            {

                if (queryCondition.Where(o => o.classID.V != null && o.classID.V == 8010).FirstOrDefault() != null)
                {
                    List<string> corpfiter = new List<string>() { "山东润德工程项目管理有限公司",
                                                                                          "青岛佳易工程管理有限公司", 
                                                                                           "山东齐信招标有限公司", 
                                                                                           "青岛建合建设项目管理有限公司",
                                                                                           "山东世元工程管理有限公司",
                                                                                           "青岛日月工程造价咨询有限公司",
                                                                                           "山东金诺建设项目管理有限公司",
                                                                                           "青岛利业建设咨询有限公司",
                                                                                           "山东三维建设项目管理有限公司",
                                                                                           "青岛信达工程管理有限公司",
                                                                                           "青岛信科达工程咨询有限公司",
                                                                                           "青岛精信工程管理有限公司",
                                                                                           "青岛建通工程招标咨询有限公司",
                                                                                           "青岛海易建设项目管理咨询有限公司",
                                                                                           "青岛正阳工程造价咨询事务所有限公司",
                                                                                           "山东东成建设咨询有限公司",
                                                                                           "青岛市昊金海建设项目管理有限公司",
                                                                                           "山东中钢招标有限公司"
                };
                    query = query.Where(o => corpfiter.Contains(o.CorpName));
                }
            }
            var result = new List<DTO.CompanyInfo>();
            if (pageSize > 0)
            {
                result = query.Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }
            string aaa = query.ToString();
            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                        flowAreaCode,
                        item.classID.ToString(),
                        item.FlowCode);
                }
                catch
                {

                }
            }
            return result;
        }

        public override int GetPortalCorpCount(IList<QueryPortalCompanyInfoCondition> queryCondition, string flowAreaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            if (!string.IsNullOrEmpty(flowAreaCode))
            {
                query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == flowAreaCode
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode
                            #endregion
                        };
            }
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            if (queryCondition.Where(o => o.classID.V != null && o.classID.V == 2509).FirstOrDefault() != null)
            {
                query = query.OrderByDescending(o => o.ID);
            }
            else
            {
                query = query.Where(s => !string.IsNullOrEmpty(s.GradeCode) && !string.IsNullOrEmpty(s.GradeName));
            }
            if (flowAreaCode != "06")
            {

                if (queryCondition.Where(o => o.classID.V != null && o.classID.V == 8010).FirstOrDefault() != null)
                {
                    List<string> corpfiter = new List<string>() { "山东润德工程项目管理有限公司",
                                                              "青岛佳易工程管理有限公司", 
                                                              "山东齐信招标有限公司", 
                                                              "青岛建合建设项目管理有限公司",
                                                              "山东世元工程管理有限公司",
                                                              "青岛日月工程造价咨询有限公司",
                                                              "山东金诺建设项目管理有限公司",
                                                              "青岛利业建设咨询有限公司",
                                                              "山东三维建设项目管理有限公司",
                                                              "青岛信达工程管理有限公司",
                                                              "青岛信科达工程咨询有限公司",
                                                              "青岛精信工程管理有限公司",
                                                              "青岛建通工程招标咨询有限公司",
                                                              "青岛海易建设项目管理咨询有限公司",
                                                              "青岛正阳工程造价咨询事务所有限公司",
                                                              "山东东成建设咨询有限公司",
                                                              "青岛市昊金海建设项目管理有限公司",
                                                              "山东中钢招标有限公司"
                };
                    query = query.Where(o => corpfiter.Contains(o.CorpName));
                }
            }
            return query.Count();
        }

        #region 获取企业考核列表
        public override List<CompanyInfo> GetItemBikedList(int pageSize, int pageNum, List<QueryCompanyInfoCondition> condition, string areaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query1 = from item in dbContext.h_ItemBiked
                         where item.bValid == 1 && item.AreaCode == "0209"
                         group item by item.KHObjectID into g1
                         select new { g1.Key, score1 = g1.Sum(s => s.ScoreType == 1 ? s.Score : 0 - s.Score) };
            var queryCard = from item in dbContext.h_ItemBiked
                            where item.bValid == 1
                            group item by new { item.KHObjectID } into g1
                            select new
                            {
                                g1.Key.KHObjectID,
                                NoCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.NoCard),
                                Warning = g1.Count(o => o.FlagBiked == (byte)FlagBiked.Warning),
                                YellowCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.YellowCard),
                                RedCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.RedCard)
                            };
            var query2 = from item in dbContext.e_DeDuck
                         group item by item.CorpUserGuid into g1
                         select new { g1.Key, score2 = g1.Sum(s => s.Score) };
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        join s1 in query1 on user.DogID equals s1.Key
                        into result1
                        from r1 in result1.DefaultIfEmpty()
                        join s2 in query2 on company.CorpUserGuid equals s2.Key
                        into result2
                        from r2 in result2.DefaultIfEmpty()
                        join card in queryCard on user.DogID equals card.KHObjectID
                        into result3
                        from r3 in result3.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = r2.score2 ?? 0,////不良行为扣分
                            Score3 = 100 - (r2.score2 ?? 0) + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r3.NoCard == null ? 0 : r3.NoCard,////不挂牌数量
                            Warnning = r3.Warning == null ? 0 : r3.Warning,////警告数量
                            YellowCard = r3.YellowCard == null ? 0 : r3.YellowCard,////黄牌数量
                            RedCard = r3.RedCard == null ? 0 : r3.RedCard////红牌数量
                            #endregion
                        };

            if (areaCode == "0209")
            {
                #region 胶州交易中心特殊处理

                var dbCompanies1 = dbContext.CompanyInfoFlowJZ;
                query = from company in dbCompanies1
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        join s1 in query1 on user.DogID equals s1.Key
                        into result1
                        from r1 in result1.DefaultIfEmpty()
                        join s2 in query2 on company.CorpUserGuid equals s2.Key
                        into result2
                        from r2 in result2.DefaultIfEmpty()
                        join card in queryCard on user.DogID equals card.KHObjectID
                        into result3
                        from r3 in result3.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = r2.score2 ?? 0,////不良行为扣分
                            Score3 = 100 - (r2.score2 ?? 0) + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r3.NoCard == null ? 0 : r3.NoCard,////不挂牌数量
                            Warnning = r3.Warning == null ? 0 : r3.Warning,////警告数量
                            YellowCard = r3.YellowCard == null ? 0 : r3.YellowCard,////黄牌数量
                            RedCard = r3.RedCard == null ? 0 : r3.RedCard////红牌数量
                            #endregion
                        };

                #endregion
            }

            if (condition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(condition);
                if (condition.Where(o => o.classID != null && o.classID.V != null && o.classID.V == 8010).FirstOrDefault() != null)
                {
                    List<string> corpfiter = new List<string>() { "山东润德工程项目管理有限公司",
                                                                  "青岛佳易工程管理有限公司", 
                                                                   "山东齐信招标有限公司", 
                                                                   "青岛建合建设项目管理有限公司",
                                                                   "山东世元工程管理有限公司",
                                                                   "青岛日月工程造价咨询有限公司",
                                                                   "山东金诺建设项目管理有限公司",
                                                                   "青岛利业建设咨询有限公司",
                                                                   "山东三维建设项目管理有限公司",
                                                                   "青岛信达工程管理有限公司",
                                                                   "青岛信科达工程咨询有限公司",
                                                                   "青岛精信工程管理有限公司",
                                                                   "青岛建通工程招标咨询有限公司",
                                                                   "青岛海易建设项目管理咨询有限公司",
                                                                   "青岛正阳工程造价咨询事务所有限公司",
                                                                   "山东东成建设咨询有限公司",
                                                                   "青岛市昊金海建设项目管理有限公司",
                                                                   "山东中钢招标有限公司"
                };
                    query = query.Where(o => corpfiter.Contains(o.CorpName));
                }
            }

            if (pageSize > 0)
            {
                return query.OrderByDescending(o => o.Score3).ThenBy(o => o.AreaCode).ThenBy(o => o.CorpName).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public override int GetItemBikedCount(List<QueryCompanyInfoCondition> condition, string areaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var query1 = from item in dbContext.h_ItemBiked
                         where item.bValid == 1
                         group item by item.KHObjectID into g1
                         select new { g1.Key, score1 = g1.Sum(s => s.ScoreType == 1 ? s.Score : 0 - s.Score) };
            var queryCard = from item in dbContext.h_ItemBiked
                            where item.bValid == 1
                            group item by new { item.KHObjectID } into g1
                            select new
                            {
                                g1.Key.KHObjectID,
                                NoCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.NoCard),
                                Warning = g1.Count(o => o.FlagBiked == (byte)FlagBiked.Warning),
                                YellowCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.YellowCard),
                                RedCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.RedCard)
                            };
            var query2 = from item in dbContext.e_DeDuck
                         group item by item.CorpUserGuid into g1
                         select new { g1.Key, score2 = g1.Sum(s => s.Score) };
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        join s1 in query1 on user.DogID equals s1.Key
                        into result1
                        from r1 in result1.DefaultIfEmpty()
                        join s2 in query2 on company.CorpUserGuid equals s2.Key
                        into result2
                        from r2 in result2.DefaultIfEmpty()
                        join card in queryCard on user.DogID equals card.KHObjectID
                        into result3
                        from r3 in result3.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = r2.score2 ?? 0,////不良行为扣分
                            Score3 = 100 - (r2.score2 ?? 0) + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r3.NoCard == null ? 0 : r3.NoCard,////不挂牌数量
                            Warnning = r3.Warning == null ? 0 : r3.Warning,////警告数量
                            YellowCard = r3.YellowCard == null ? 0 : r3.YellowCard,////黄牌数量
                            RedCard = r3.RedCard == null ? 0 : r3.RedCard////红牌数量
                            #endregion
                        };

            if (areaCode == "0209")
            {
                #region 胶州交易中心特殊处理

                var dbCompanies1 = dbContext.CompanyInfoFlowJZ;
                query = from company in dbCompanies1
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        join s1 in query1 on user.DogID equals s1.Key
                        into result1
                        from r1 in result1.DefaultIfEmpty()
                        join s2 in query2 on company.CorpUserGuid equals s2.Key
                        into result2
                        from r2 in result2.DefaultIfEmpty()
                        join card in queryCard on user.DogID equals card.KHObjectID
                        into result3
                        from r3 in result3.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = r2.score2 ?? 0,////不良行为扣分
                            Score3 = 100 - (r2.score2 ?? 0) + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r3.NoCard == null ? 0 : r3.NoCard,////不挂牌数量
                            Warnning = r3.Warning == null ? 0 : r3.Warning,////警告数量
                            YellowCard = r3.YellowCard == null ? 0 : r3.YellowCard,////黄牌数量
                            RedCard = r3.RedCard == null ? 0 : r3.RedCard////红牌数量
                            #endregion
                        };

                #endregion
            }

            if (condition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(condition);
                if (condition.Where(o => o.classID.V != null && o.classID.V == 8010).FirstOrDefault() != null)
                {
                    List<string> corpfiter = new List<string>() { "山东润德工程项目管理有限公司",
                                                                                          "青岛佳易工程管理有限公司", 
                                                                                           "山东齐信招标有限公司", 
                                                                                           "青岛建合建设项目管理有限公司",
                                                                                           "山东世元工程管理有限公司",
                                                                                           "青岛日月工程造价咨询有限公司",
                                                                                           "山东金诺建设项目管理有限公司",
                                                                                           "青岛利业建设咨询有限公司",
                                                                                           "山东三维建设项目管理有限公司",
                                                                                           "青岛信达工程管理有限公司",
                                                                                           "青岛信科达工程咨询有限公司",
                                                                                           "青岛精信工程管理有限公司",
                                                                                           "青岛建通工程招标咨询有限公司",
                                                                                           "青岛海易建设项目管理咨询有限公司",
                                                                                           "青岛正阳工程造价咨询事务所有限公司",
                                                                                           "山东东成建设咨询有限公司",
                                                                                           "青岛市昊金海建设项目管理有限公司",
                                                                                           "山东中钢招标有限公司"
                };
                    query = query.Where(o => corpfiter.Contains(o.CorpName));
                }
            }
            return query.Count();
        }

        public override List<tb_emp_expert> GetEmpExpertList(int pageSize, int pageNum, List<QueryEmpExpertCondition> condition, string areaCode)
        {
            var score = from item in dbContext.h_ItemBiked
                        where item.bValid == 1
                        group item by item.KHObjectID into g1
                        select new
                        {
                            g1.Key,
                            score1 = g1.Sum(s => s.ScoreType == 1 ? s.Score : 0 - s.Score),
                            NoCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.NoCard),
                            Warning = g1.Count(o => o.FlagBiked == (byte)FlagBiked.Warning),
                            YellowCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.YellowCard),
                            RedCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.RedCard)
                        };
            var query = from expert in dbContext.tb_emp_expert
                        join s1 in score on expert.ID equals s1.Key
                        into result1
                        from r1 in result1.DefaultIfEmpty()
                        select new tb_emp_expert()
                        {
                            ExpertName = expert.ExpertName,
                            Sex = expert.Sex,
                            CellPhone = expert.CellPhone,
                            CompanyName = expert.CompanyName,
                            EmpGuid = expert.EmpGuid,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = 0,////不良行为扣分
                            Score3 = 100 - 0 + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r1.NoCard == null ? 0 : r1.NoCard,////不挂牌数量
                            Warnning = r1.Warning == null ? 0 : r1.Warning,////警告数量
                            YellowCard = r1.YellowCard == null ? 0 : r1.YellowCard,////黄牌数量
                            RedCard = r1.RedCard == null ? 0 : r1.RedCard////红牌数量
                        };
            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<tb_emp_expert>(condition);
            }
            return query.OrderByDescending(o => o.Score3).ThenBy(o => o.ExpertName).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
        }

        public override int GetEmpExpertCount(List<QueryEmpExpertCondition> condition, string areaCode)
        {
            var score = from item in dbContext.h_ItemBiked
                        where item.bValid == 1
                        group item by item.KHObjectID into g1
                        select new
                        {
                            g1.Key,
                            score1 = g1.Sum(s => s.ScoreType == 1 ? s.Score : 0 - s.Score),
                            NoCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.NoCard),
                            Warning = g1.Count(o => o.FlagBiked == (byte)FlagBiked.Warning),
                            YellowCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.YellowCard),
                            RedCard = g1.Count(o => o.FlagBiked == (byte)FlagBiked.RedCard)
                        };
            var query = from expert in dbContext.tb_emp_expert
                        join s1 in score on expert.ID equals s1.Key
                       into result1
                        from r1 in result1.DefaultIfEmpty()
                        select new tb_emp_expert()
                        {
                            ExpertName = expert.ExpertName,
                            Sex = expert.Sex,
                            CellPhone = expert.CellPhone,
                            CompanyName = expert.CompanyName,
                            EmpGuid = expert.EmpGuid,
                            Score1 = r1.score1 ?? 0,////一标一考核加减分
                            Score2 = 0,////不良行为扣分
                            Score3 = 100 - 0 + (r1.score1 ?? 0),////总分为100-不良行为扣分+一标一考核加减分
                            NoCard = r1.NoCard == null ? 0 : r1.NoCard,////不挂牌数量
                            Warnning = r1.Warning == null ? 0 : r1.Warning,////警告数量
                            YellowCard = r1.YellowCard == null ? 0 : r1.YellowCard,////黄牌数量
                            RedCard = r1.RedCard == null ? 0 : r1.RedCard////红牌数量
                        };
            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<tb_emp_expert>(condition);
            }
            return query.Count();
        }
        #endregion
        #region 通知管理
        public override List<tb_Notice> GetNoticeList(out int count, int pageSize, int pageNum, List<QueryNoticeInfoCondition> condition, string areaCode)
        {
            var query = from notice in dbContext.tb_Notice
                        where notice.IsDel != true
                        select new tb_Notice()
                        {
                            ID = notice.ID,
                            KeyGuid = notice.KeyGuid,
                            Topic = notice.Topic,
                            Content = notice.Content,
                            SortIndex = notice.SortIndex,
                            IsrtUser = notice.IsrtUser,
                            IsrtDate = notice.IsrtDate,
                            ClassId = notice.ClassId,
                            Type = notice.Type,
                            Remark = notice.Remark,
                            Code = notice.Code,
                            UpdateDate = notice.UpdateDate,
                            TopicType = notice.TopicType
                        };
            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<tb_Notice>(condition);
            }
            count = query.Count();
            query = query.OrderByDescending(o => o.IsrtDate).Skip((pageNum - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }

        public override tb_Notice GetNotice(string guid)
        {
            DbSet<tb_Notice_Zbdlry> dbNotice = dbContext.tb_Notice;
            Guid keyGuid = Guid.Empty;
            if (string.IsNullOrEmpty(guid))
            {
                return null;
            }
            if (!Guid.TryParse(guid, out keyGuid))
            {
                return null;
            }
            var query = from notice in dbNotice
                        where notice.KeyGuid == keyGuid && notice.IsDel != true
                        select new tb_Notice()
                        {
                            ID = notice.ID,
                            KeyGuid = notice.KeyGuid,
                            Topic = notice.Topic,
                            Content = notice.Content,
                            SortIndex = notice.SortIndex,
                            IsrtUser = notice.IsrtUser,
                            IsrtDate = notice.IsrtDate,
                            ClassId = notice.ClassId,
                            Type = notice.Type,
                            Remark = notice.Remark,
                            Code = notice.Code,
                            UpdateDate = notice.UpdateDate,
                            TopicType = notice.TopicType
                        };
            var ret = query.FirstOrDefault();
            return ret;
        }

        public override OperationResult SaveNoticeInfo(tb_Notice noticeModel)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "操作失败";
            try
            {
                tb_Notice_Zbdlry noticeEntity = new tb_Notice_Zbdlry();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(noticeModel, noticeEntity);
                if (noticeEntity.KeyGuid == Guid.Empty)
                {
                    noticeEntity.KeyGuid = Guid.NewGuid();
                }
                noticeEntity.IsrtDate = DateTime.Now;
                noticeEntity.IsDel = false;
                dbContext.Entry(noticeEntity).State = noticeEntity.ID == 0 ? EntityState.Added : EntityState.Modified;
                dbContext.SaveChanges();
                ret.Message = "操作成功";
                ret.ReturnValue = 1;
                ret.Result = true;
            }
            catch (Exception err)
            {
                ret.Result = false;
                ret.Message = err.Message;
                ret.ReturnValue = 0;
            }
            return ret;
        }

        public override OperationResult DeleteNotice(string keyGuid)
        {
            DbSet<tb_Notice_Zbdlry> dbNotice = dbContext.tb_Notice;
            DTO.OperationResult result = new OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            Guid guid = Guid.Empty;
            if (string.IsNullOrEmpty(keyGuid))
            {
                result.Message = "参数不能为空";
                result.Result = false;
                result.ReturnValue = 0;
                return result;
            }
            if (!Guid.TryParse(keyGuid, out guid))
            {
                result.Message = "参数格式不正确";
                result.Result = false;
                result.ReturnValue = 0;
                return result;
            }
            try
            {
                var notice = dbNotice.Where(o => o.KeyGuid == guid).FirstOrDefault();
                if (notice != null)
                {
                    notice.IsDel = true;
                }
                dbContext.SaveChanges();
                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }
        #endregion
        EnterpriseDALWh enterpriseDAL = new EnterpriseDALWh();

        public override List<DTO.CorpBzjInfo> GetCorBzjList(out int count, int pageIndex, int pageSize, string condition, string areaCode)
        {

            List<DTO.CorpBzjInfo> result = new List<DTO.CorpBzjInfo>();
            var query = enterpriseDAL.GetCorBzjList(out count, pageIndex, pageSize, condition, areaCode);
            foreach (Entity.CorpBzjInfo item in query)
            {
                DTO.CorpBzjInfo model = new DTO.CorpBzjInfo();
                model.bID = item.bID;
                model.BidName = item.BidName;
                model.CorpName = item.CorpName;
                model.pID = item.pID;
                model.ProjectName = item.ProjectName;
                result.Add(model);
            }
            return result;

            //  return enterpriseDAL.GetCorBzjList(out count, pageIndex, pageSize, condition, areaCode);
        }

        public override List<string> GetCorBzjGroupList(out int count, int pageIndex, int pageSize, string condition, string areaCode)
        {
            //CorpBzjDate model = new CorpBzjDate();
            //List<CorpBzjDate> result = new List<CorpBzjDate>();
            //var query = enterpriseDAL.GetCorBzjGroupList(pageIndex, pageSize, condition, areaCode);
            //foreach(Entity.CorpBzjDate item in query)
            //{
            //    model.BZJBack_Date = item.BZJBack_Date;
            //    result.Add(model);     
            //}
            //return result;
            return enterpriseDAL.GetCorBzjGroupList(out count, pageIndex, pageSize, condition, areaCode);
        }

        #region 获取企业在所有市场的状态
        public override List<FlowStatus> GetCorpFlowStatus(string corpUserGuid, string areaCode)
        {
            areaCode = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            Guid UserGuid = Guid.Empty;
            List<FlowStatus> list = new List<FlowStatus>();
            if (Guid.TryParse(corpUserGuid, out UserGuid))
            {
                var corpInfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == UserGuid && (c.IsDel == null || c.IsDel == false)).FirstOrDefault();
                var userInfo = dbContext.T_Sys_Users.Where(u => u.UserGuid == UserGuid).FirstOrDefault();
                if (corpInfo != null && userInfo != null)
                {
                    List<Tb_FlowCode_Zbdl> flowCodes = null;
                    string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
                    if ("06" == preAreaCode)
                    {
                        int appid = 0;
                        int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                        flowCodes = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpInfo.classID
                            && (f.IsDel == null || f.IsDel == false) && f.AppID == appid).ToList();
                    }
                    else
                        flowCodes = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == corpInfo.classID && (f.IsDel == null || f.IsDel == false)).ToList();

                    BasicBLL basicBLL = new BasicBLL();
                    foreach (var flow in flowCodes)
                    {
                        FlowStatus flowStatus = new FlowStatus();
                        flowStatus.AreaCode = flow.AreaCode;
                        flowStatus.AreaCodeTitle = basicBLL.GetAreaCodeTitle(flow.AreaCode);
                        flowStatus.FlowCode = flow.FlowCode;
                        flowStatus.FlowCodeTitle = basicBLL.GetFlowCodeTitle(flow.AreaCode, corpInfo.classID.ToString(), flow.FlowCode);
                        flowStatus.CanEdit = basicBLL.GetNextFlowCode(userInfo.RoleID.ToString(),
                            "",
                            flow.AreaCode,
                            corpInfo.classID.ToString(),
                            flow.FlowCode,
                            FlowCommon.OptType.Edit).Result;
                        list.Add(flowStatus);
                    }
                }
            }
            return list;
        }

        public override List<h_ItemBiked> GetItemBikedByCorp(out int count, int pageIndex, int pageSize, string userguid)
        {
            count = 0;
            Guid guid = Guid.Empty;
            if (string.IsNullOrEmpty(userguid))
            {
                return null;
            }
            if (!Guid.TryParse(userguid, out guid))
            {
                return null;
            }
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from item in dbContext.h_ItemBiked
                        join user in dbUsers on item.KHObjectID equals user.DogID
                        join corp in dbCompanies on user.UserGuid equals corp.CorpUserGuid
                        where item.bValid == 1 && corp.CorpUserGuid == guid
                        select new DTO.h_ItemBiked()
                        {
                            ID = item.ID,
                            ItemBikedID = item.ItemBikedID,
                            Title = item.Title,
                            KHObjectID = item.KHObjectID,
                            KHObjectName = item.KHObjectName,
                            BidID = item.BidID,
                            Score = item.ScoreType == 1 ? item.Score : 0 - item.Score,
                            FlagBiked = item.FlagBiked,
                            RegisterDate = item.RegisterDate,
                            bValid = item.bValid,
                            RightCode = item.RightCode,
                            AreaCode = item.AreaCode,
                            KeyGUID = item.KeyGUID,
                            CreditCode = item.CreditCode,
                            IsrtUser = item.IsrtUser,
                            IsrtUserName = item.IsrtUserName,
                            ScoreType = item.ScoreType,
                            ItemTitle = corp.CorpName
                        };
            count = query.Count();
            if (pageSize > 0)
            {
                query = query.OrderByDescending(o => o.RegisterDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                query.OrderByDescending(o => o.RegisterDate).ToList();
            }
            return query.ToList();
        }
        #endregion

        #region 公文新闻
        public override List<b_NewsTable> GetNewsList(out int count, int pageNum, int pageSize, List<QueryNewsInfoCondition> condition, string areaCode)
        {
            var query = from news in dbContext.b_NewsTable
                        where news.IsDel == false || news.IsDel == null
                        select new b_NewsTable()
                        {
                            ID = news.ID,
                            FileCode = news.FileCode,
                            FileTitle = news.FileTitle,
                            FileTitleAcctached = news.FileTitle,
                            FileContent = news.FileContent,
                            Register = news.Register,
                            TreeRootID = news.TreeRootID,
                            TreeID = news.TreeID,
                            Author = news.Author,
                            bFocus = news.bFocus,
                            PicFileName = news.PicFileName,
                            bHtml = news.bHtml,
                            ClassID = news.ClassID,
                            ClickCount = news.ClickCount,
                            bShowInList = news.bShowInList,
                            GradeKind = news.GradeKind,
                            AreaID = news.AreaID,
                            endDate = news.endDate,
                            FileSendTo = news.FileSendTo,
                            TopicWord = news.TopicWord,
                            LinkInfo = news.LinkInfo,
                            strFlag = news.strFlag,
                            bStatus = news.bStatus,
                            IndexCode = news.IndexCode,
                            bImportant = news.bImportant,
                            attachedUrl = news.attachedUrl,
                            attachedName = news.attachedName,
                            bflag = news.bflag,
                            pubDate = news.pubDate,
                            AppId = news.AppId,
                            IsDel = news.IsDel

                        };
            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<b_NewsTable>(condition);
            }
            count = query.Count();
            query = query.OrderByDescending(o => o.pubDate).Skip((pageNum - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }

        public override b_NewsTable GetNewsInfo(int id)
        {
            DbSet<b_NewsTable_Zbdlry> dbNews = dbContext.b_NewsTable;
            var query = from news in dbNews
                        where news.ID == id && (news.IsDel == false || news.IsDel == null)
                        select new b_NewsTable()
                        {
                            ID = news.ID,
                            FileCode = news.FileCode,
                            FileTitle = news.FileTitle,
                            FileTitleAcctached = news.FileTitle,
                            FileContent = news.FileContent,
                            Register = news.Register,
                            TreeRootID = news.TreeRootID,
                            TreeID = news.TreeID,
                            Author = news.Author,
                            bFocus = news.bFocus,
                            PicFileName = news.PicFileName,
                            bHtml = news.bHtml,
                            ClassID = news.ClassID,
                            ClickCount = news.ClickCount,
                            bShowInList = news.bShowInList,
                            GradeKind = news.GradeKind,
                            AreaID = news.AreaID,
                            endDate = news.endDate,
                            FileSendTo = news.FileSendTo,
                            TopicWord = news.TopicWord,
                            LinkInfo = news.LinkInfo,
                            strFlag = news.strFlag,
                            bStatus = news.bStatus,
                            IndexCode = news.IndexCode,
                            bImportant = news.bImportant,
                            attachedUrl = news.attachedUrl,
                            attachedName = news.attachedName,
                            bflag = news.bflag,
                            pubDate = news.pubDate,
                            AppId = news.AppId,
                            IsDel = news.IsDel
                        };
            var ret = query.FirstOrDefault();
            return ret;
        }

        public override OperationResult SaveNewsInfo(b_NewsTable newsModel)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "操作失败";
            try
            {
                b_NewsTable_Zbdlry newsEntity = new b_NewsTable_Zbdlry();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(newsModel, newsEntity);
                newsEntity.GradeKind = 0;
                newsEntity.bHtml = true;
                newsEntity.Register = DateTime.Now;
                newsEntity.IsDel = false;
                dbContext.Entry(newsEntity).State = newsEntity.ID == 0 ? EntityState.Added : EntityState.Modified;
                dbContext.SaveChanges();
                ret.Message = "操作成功";
                ret.ReturnValue = 1;
                ret.Result = true;
            }
            catch (Exception err)
            {
                ret.Result = false;
                ret.Message = err.Message;
                ret.ReturnValue = 0;
            }
            return ret;
        }

        public override OperationResult DeleteNews(int id)
        {
            DbSet<b_NewsTable_Zbdlry> dbNews = dbContext.b_NewsTable;
            DTO.OperationResult result = new OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            Guid guid = Guid.Empty;
            try
            {
                var news = dbNews.Where(o => o.ID == id).FirstOrDefault();
                if (news != null)
                {
                    news.IsDel = true;
                }
                dbContext.SaveChanges();
                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }

        #endregion

        #region 企业注册审核(烟台)
        public override List<CompanyInfo> GetCorpRegListYT(out int count, int pageNum, int pageSize, List<QueryCompanyInfoCondition> condition, string areaCode, string flowClassId, string roleId)
        {
            var dbCompanies = dbContext.CompanyRegFlowYT;
            var dbUsers = dbContext.T_Sys_Users;
            var dbCMFlow = dbContext.CMFlow;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        //join cmflow in dbCMFlow on company.CorpUserGuid equals cmflow.EntityID
                        where company.IsDel == false
                        //&& cmflow.AppID == 156
                        select new CompanyInfo
                       {
                           #region 封装实体
                           ID = company.ID,
                           classID = company.classID,
                           Dogid = company.dogid,
                           CorpGuid = company.CorpGuid,
                           CorpUserGuid = company.CorpUserGuid,
                           CorpName = company.CorpName,
                           RoleId = user.RoleID,
                           AreaCode = company.AreaCode,
                           AreaCode2 = company.AreaCode2,
                           Address = company.Address,
                           ZipCode = company.ZipCode,
                           NetAddress = company.NetAddress,
                           Email = company.Email,
                           LinkMan1 = company.LinkMan1,
                           Tel1 = company.Tel1,
                           Linkman = company.Linkman,
                           Tel = company.Tel,
                           Fax = company.Fax,
                           SecurityTitleGetDate = company.SecurityTitleGetDate,
                           SecurityCode = company.SecurityCode,
                           Introduction = company.Introduction,
                           EndTime = company.EndTime,
                           PassNum = company.PassNum,
                           QualificationNum = company.QualificationNum,
                           QualificationLevel = company.QualificationLevel,
                           BussinessNum = company.BussinessNum,
                           FoundTime = company.FoundTime,
                           BussinessArea = company.BussinessArea,
                           Type = company.Type,
                           FlowCode = company.RealFlowCode,
                           RegisterMoney = company.RegisterMoney,
                           bISO14000 = company.bISO14000,
                           bISO9000 = company.bISO9000,
                           bISO9001 = company.bISO9001,
                           bOHSMS18000 = company.bOHSMS18000,
                           QualityState = company.QualityState,
                           bCanBid = company.bCanBid,
                           OrginazationCode = company.OrginazationCode,
                           GetDate = user.RegisterDate,
                           FlowCodeType = company.FlowCodeType
                           #endregion
                       };

            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(condition);
            }

            if (flowClassId == "-1")
            {
                string msg = string.Empty;
                List<string> classidList = FlowCommon.FlowHelper.GetClassIDListbyType(areaCode, "corpReg", roleId, out msg);
                List<int> classidListInt = new List<int>();
                foreach (var item in classidList)
                {
                    classidListInt.Add(int.Parse(item));
                }
                query = query.Where(f => classidListInt.Contains((int)f.FlowCodeType));
            }
            else
            {
                int classId = int.Parse(flowClassId);
                query = query.Where(f => f.FlowCodeType == classId);

            }
            string aaa = query.ToString();

            count = query.Count();
            query = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize);
            var result = query.ToList();
            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = transFlowcode(
                       item.FlowCode,
                       areaCode,
                       item.FlowCodeType.ToString()
                       );

                }
                catch
                {

                }
            }

            return result;
        }

        private string transFlowcode(string flowCode, string areaCode, string classid)
        {
            if (string.IsNullOrEmpty(flowCode))
            {
                return "";
            }
            string returnValue = string.Empty;
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string msg = string.Empty;

            dict = FlowCommon.FlowHelper.GetAllBusinessStatus(areaCode, classid, out msg);

            if (dict != null && !flowCode.StartsWith("1,") && dict.ContainsKey(flowCode))
            {
                returnValue = dict[flowCode];
                return returnValue;

            }
            if (dict != null && flowCode.StartsWith("1,"))
            {

                foreach (var item in dict)
                {
                    if (item.Key.StartsWith("1,"))
                    {
                        returnValue = dict[item.Key];
                        return returnValue;
                    }
                }

            }
            return returnValue;
        }

        public override List<CompanyInfo> GetManagerRegListYT(out int count, int pageNum, int pageSize, List<QueryCompanyInfoCondition> condition, string areaCode)
        {
            var dbDetail = dbContext.UserDetail;
            var dbFlow = dbContext.FlowCodes;

            var query =
                from user in dbContext.T_Sys_Users
                join detail in dbDetail on user.UserGuid equals detail.UserGuid
                join flow in dbFlow on detail.ObjectID equals flow.ObjectId
                where flow.IsDel == false && flow.CodeType == 10006
                select new CompanyInfo
                {
                    #region 封装实体
                    ID = detail.ID,
                    CorpUserGuid = detail.UserGuid,
                    CorpName = detail.CorpName,
                    Tel = detail.Tel,
                    Introduction = detail.Name, //暂时用这个代替 以后时间充裕了再添加新Entity类
                    FlowCode = flow.FlowCode,
                    GetDate = detail.SignDate
                    #endregion
                };


            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(condition);
            }

            count = query.Count();
            query = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize);
            var result = query.ToList();
            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                        "06",
                        "10006",
                        item.FlowCode);
                }
                catch
                {

                }
            }
            return result;
        }

        public override DTO.OperationResult CorpRegAudit(string corpUserGuid
          , string areaCode
          , User_Log log
          , string flowCode
          , string description
          , bool isFinal
          , string classId)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////市场范围地区
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            Guid cGuid = Guid.Empty;
            Guid.TryParse(corpUserGuid, out cGuid);
            Tb_Corp_CompanyInfo_Zbdl corpinfo = dbContext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == cGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();
            int functionId = -1;
            if (string.IsNullOrEmpty(log.FunctionId) || !int.TryParse(log.FunctionId, out functionId))
            {
                result.Message = "审核企业注册信息失败：操作类型错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            Fly.Common.WorkFlow.OptType opt = (Fly.Common.WorkFlow.OptType)functionId;
            string optTitle = GetOptTitle(opt);
            if (corpinfo == null)
            {
                result.Message = optTitle + "企业注册信息失败：未检测到企业信息";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(log.IsrtUserRole))
            {
                result.Message = optTitle + "企业注册信息失败：审核用户角色Id无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(corpinfo.classID.ToString()))
            {
                result.Message = optTitle + "企业注册信息失败：被审核企业classid无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            string corpId = corpinfo.CorpUserGuid.ToString();
            int codeType = int.Parse(classId);
            Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.Where(f => f.ObjectId == corpId && f.CodeType == codeType && f.IsDel == false).FirstOrDefault();
            if (flow == null)
            {
                ////状态为非审核状态
                ////日志
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败", corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Message = optTitle + "企业注册信息失败：企业未上报或状态错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (!string.IsNullOrEmpty(flow.FlowCode))
            {
                if (flowCode.StartsWith("1,") && opt == Fly.Common.WorkFlow.OptType.Reject)
                {
                    opt = Fly.Common.WorkFlow.OptType.UnlockReject;
                }
            }
            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(log.IsrtUserRole, "", areaCode, classId, flow.FlowCode, opt);
            if (!nextNode.Result)
            {
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败:" + nextNode.Message, corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            if (nextNode.IsFinal)
            {
                OperationResult retOrder = OrderGenerate_lc(corpinfo.CorpGuid, "14");
                if ((int)retOrder.ReturnValue != 0)
                {
                    result.Result = false;
                    result.Message = retOrder.Message;
                    return result;
                }
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////企业状态
                    flow.FlowCode = nextNode.NextFlowCode;
                    if (corpinfo.AreaCode.StartsWith(preArea))
                    {
                        ////企业注册地主管审核
                        corpinfo.FlowCode = nextNode.NextFlowCode;
                    }
                    dbContext.SaveChanges();
                    ////日志
                    baseBll.InsertDetailUserLog(optTitle + "企业注册信息成功！" + log.Content, corpUserGuid, classId, log.FunctionId, log);
                    tran.Commit();
                    result.Message = optTitle + "企业注册信息成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = optTitle + "企业注册信息失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        private OperationResult OrderGenerate_YT(Guid CorpGuid, string areacode)
        {
            OperationResult ret = new OperationResult();
            ret.ReturnValue = -9;
            try
            {
                Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.FirstOrDefault(m => m.CorpGuid == CorpGuid);
                OrderContext orderContext = new OrderContext();
                var hasold = orderContext.CAPayInfoSub.Any(m => m.SourceID == corp.ID && m.bCAKind == "E25");
                if (hasold)
                {
                    ret.ReturnValue = -1;
                    ret.Message = "订单已存在";
                    return ret;
                }
                Entity.ZBDLRY.tb_CAPayInfo order = new Entity.ZBDLRY.tb_CAPayInfo();
                order.AreaCode = areacode;  // corp.AreaCode;  ///
                order.bCAStatus = 2;//1：提示  2：线下 3：财务确认 4：制Key
                order.bcorpkind = int.Parse(corp.Type);
                order.caResult = "";
                order.Code = DateTime.Now.ToString("yyMMddHHmmssff") + "01";
                order.CorpUserGuid = corp.CorpUserGuid;
                order.FlowCode = "0,019,;4000";
                order.iTitle = corp.CorpName;
                order.KeyGUID = Guid.NewGuid();
                order.LinkPerson = corp.LinkMan1;
                order.mobileTel = "";
                order.officeTel = corp.Tel;
                order.OptDate = DateTime.Now;
                order.postcode = corp.ZipCode;
                order.RegisterDate = DateTime.Now;
                order.RightCode = 1;
                order.SendAddress = corp.Address;
                order.SumPay = 2500;
                order.TransDate = DateTime.Parse("2011-1-1");
                order.GroupCode = "CA01";
                order.CurrentAreaCode = areacode;


                Entity.ZBDLRY.tb_CAPayInfo_Sub detail = new Entity.ZBDLRY.tb_CAPayInfo_Sub();
                detail.KeyGUID = Guid.NewGuid();
                detail.Remark = "";
                detail.RightCode = 1;
                detail.SourceID = corp.ID;
                detail.SumPay = 2500;
                detail.Title = corp.CorpName;
                detail.bCAKind = "E25";
                detail.bCAStatus = 2;
                detail.bStatus = 1;
                detail.btype = 0;
                detail.FlowCode = "0,019,;4000";

                orderContext.CAPayInfo.Add(order);
                orderContext.CAPayInfoSub.Add(detail);
                DbConnection con = ((IObjectContextAdapter)orderContext).ObjectContext.Connection;
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {


                    orderContext.SaveChanges();
                    detail.treeID = order.ID;
                    orderContext.SaveChanges();
                    tran.Commit();

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                }
                ret.ReturnValue = 0;
                con.Close();
            }
            catch (Exception ex)
            {
                ret.ReturnValue = -2;
                ret.Message = ex.Message;
            }
            return ret;
        }

        public override DTO.OperationResult ManagerRegAudit(string userGuid
        , string areaCode
        , User_Log log
        , string flowCode
        , string description
        , bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////市场范围地区
            string preArea = string.IsNullOrEmpty(areaCode) ? "" : (areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode);
            Guid guid = Guid.Empty;
            Guid.TryParse(userGuid, out guid);
            T_Sys_UsersInfo userinfo = dbContext.UserDetail.Where(o => o.UserGuid == guid).FirstOrDefault();
            int functionId = -1;
            if (string.IsNullOrEmpty(log.FunctionId) || !int.TryParse(log.FunctionId, out functionId))
            {
                result.Message = "审核主管用户注册信息失败：操作类型错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            Fly.Common.WorkFlow.OptType opt = (Fly.Common.WorkFlow.OptType)functionId;
            string optTitle = GetOptTitle(opt);
            if (userinfo == null)
            {
                result.Message = optTitle + "主管用户注册信息失败：未检测到主管用户信息";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (String.IsNullOrEmpty(log.IsrtUserRole))
            {
                result.Message = optTitle + "主管用户注册信息失败：审核用户角色Id无效";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            string strUserGuid = userinfo.UserGuid.ToString();
            Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.Where(f => f.ObjectId == strUserGuid && f.CodeType == 10006 && f.IsDel == false).FirstOrDefault();
            if (flow == null)
            {
                ////状态为非审核状态
                ////日志
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败", corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Message = optTitle + "主管用户注册信息失败：主管用户未上报或状态错误";
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
            if (!string.IsNullOrEmpty(flow.FlowCode))
            {
                if (flowCode.StartsWith("1,") && opt == Fly.Common.WorkFlow.OptType.Reject)
                {
                    opt = Fly.Common.WorkFlow.OptType.UnlockReject;
                }
            }
            var nextNode = FlowCommon.FlowHelper.GetNextFlowCode(log.IsrtUserRole, "", areaCode, "10006", flow.FlowCode, opt);
            if (!nextNode.Result)
            {
                //baseBll.InsertDetailUserLog(optTitle + "企业信息失败:" + nextNode.Message, corpUserGuid, corpinfo.classID.ToString(), "5", log);
                result.Result = false;
                result.Message = nextNode.Message;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////审核状态
                    flow.FlowCode = nextNode.NextFlowCode;
                    dbContext.SaveChanges();
                    ////日志
                    baseBll.InsertDetailUserLog(optTitle + "主管用户注册信息成功！" + log.Content, guid.ToString(), "10006", log.FunctionId, log);
                    tran.Commit();
                    result.Message = optTitle + "主管用户注册信息成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = optTitle + "主管用户注册信息失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 企业锁定解锁
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="bCanBid"></param>
        /// <param name="type">0解锁，1锁定</param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult SetCorpbCanBid(string corpUserGuid, string bCanBid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.Message = "企业信息不正确！";
                return result;
            }
            if (string.IsNullOrEmpty(bCanBid))
            {
                result.Result = false;
                result.Message = "提交的信息不合法！";
                return result;
            }
            try
            {
                ////查询企业
                Tb_Corp_CompanyInfo_Zbdl currentCorp = dbContext.Corp_CompanyInfos.Where(m => (m.IsDel == false || m.IsDel == null) && m.CorpUserGuid == cGuid).FirstOrDefault();
                if (currentCorp == null)
                {
                    result.Result = false;
                    result.Message = "企业信息不存在！";
                    return result;
                }

                ////修改锁定
                string bCanBids = string.IsNullOrEmpty(currentCorp.bCanBid) ? "" : currentCorp.bCanBid.Trim() + ",";
                if (bCanBids.Split(',').Contains(bCanBid.Trim()))
                {
                    bCanBids = bCanBids.Replace(bCanBid.Trim() + ",", "").TrimEnd(',');////锁定
                }
                else
                {
                    bCanBids = bCanBids.Trim() + bCanBid;////解锁
                }
                currentCorp.bCanBid = bCanBids.TrimEnd(',');
                dbContext.SaveChanges();
                result.Message += "对企业 [" + currentCorp.CorpName + "] 的操作执行成功！";
                ////2.日志
                User_Log log = new User_Log();
                log.IsrtDate = DateTime.Now;
                log.IsrtUser = currentCorp.CorpUserGuid.ToString();
                log.IsrtUserArea = areaCode;
                log.IsrtUserName = currentCorp.CorpName;
                baseBll.InsertDetailUserLog("锁定或解锁企业信息", currentCorp.CorpUserGuid.ToString(), currentCorp.classID.ToString(), "6", log);

            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "锁定或解锁企业信息失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            return result;
        }

        /// <summary>
        /// 登录时执行存储过程，复制tb_flowcode表
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="appID"></param>
        /// <param name="areaCode"></param>
        public override void GenerateFlowCodebyAppId(string userGuid, int appID, string areaCode)
        {
            enterpriseDAL.GenerateFlowCodebyAppId(userGuid, appID, areaCode);
        }

        #region 咨询互动(烟台门户)
        public override void AddConsultation(DTO.zb_Consultation submitInfo)
        {
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Entity.ZBDLRY.zb_Consultation consultation_E = new Entity.ZBDLRY.zb_Consultation();
                    EntityHelper.ConvertEntity2OtherEntity(submitInfo, consultation_E);
                    consultation_E = dbContext.ZbConsultation.Add(consultation_E);
                    dbContext.SaveChanges();
                    tran.Commit();

                }
                catch (Exception ex)
                {
                    tran.Rollback();

                }
            }
        }

        public override List<T_Sys_Users> GetConsultationUser(string roleValue, string areaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbUsers = dbContext.T_Sys_Users;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        where company.FlowAreaCode == areaCode
                        && (user.RoleID == 105 || user.RoleID == 99105)
                        && company.RealFlowCode.StartsWith("1,")
                        select new T_Sys_Users
                        {
                            #region 封装实体

                            Name = company.CorpName,
                            UserGuid = user.UserGuid
                            #endregion
                        };

            var result = new List<DTO.T_Sys_Users>();
            if (roleValue == "105,99105")
            {
                result = query.ToList();
            }
            else
            {
                List<string> nameFiter = new List<string>() { "李永刚", "李大军", "孙渤", "烟台主管" };

                query = from user in dbUsers
                        where
                            (user.RoleID == 101 || user.RoleID == 102)
                            && user.AreaCode.StartsWith("06")
                            && nameFiter.Contains(user.Name)
                        select new T_Sys_Users
                        {
                            #region 封装实体

                            Name = user.Name,
                            UserGuid = user.UserGuid
                            #endregion
                        };
                result = query.ToList();
            }
            return result;
        }

        public override List<RN.ERP.Entity.ZBDLRY.zb_Consultation> GetPortalQuestionList(string isAnswer, string type, string userGuid, string role, int pageSize, int pageIndex, string areaCode)
        {
            int ia = int.Parse(isAnswer);
            int ty = int.Parse(type);
            Guid ug = Guid.Empty;
            Guid.TryParse(userGuid, out ug);

            var ret = dbContext.ZbConsultation.Where(m => m.TypeFlag == ty);
            if (ia != 0)
            {
                ret = ret.Where(m => m.IsAnswer == ia);
            }
            if (role != "110" && role != "113")
            {
                ret = ret.Where(m => m.QuestionUserGuid == ug);
            }
            var result = ret.OrderByDescending(o => o.IsrtDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return result;
        }


        public override int GetPortalQuestionCount(string isAnswer, string type, string userGuid, string role, string areaCode)
        {
            int ia = int.Parse(isAnswer);
            int ty = int.Parse(type);
            Guid ug = Guid.Empty;
            Guid.TryParse(userGuid, out ug);

            var ret = dbContext.ZbConsultation.Where(m => m.TypeFlag == ty);
            if (ia != 0)
            {
                ret = ret.Where(m => m.IsAnswer == ia);
            }
            if (role != "110" && role != "113")
            {
                ret = ret.Where(m => m.QuestionUserGuid == ug);
            }
            var result = ret.Count();
            return result;
        }


        public override RN.ERP.Entity.ZBDLRY.zb_Consultation GetPortalQuestion(string id, string areaCode)
        {
            int cid = int.Parse(id);
            var ret = dbContext.ZbConsultation.Where(m => m.ID == cid).FirstOrDefault();
            return ret;
        }

        public override List<RN.ERP.Entity.ZBDLRY.zb_Consultation_Answer> GetPortalAnswerList(string id, int pageSize, int pageIndex, string areaCode)
        {
            int cid = int.Parse(id);
            var ret = dbContext.ZbConsultationAnswer.Where(m => m.ConsultationId == cid);
            var result = ret.OrderByDescending(o => o.IsrtDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return result;
        }

        public override int GetPortalAnswerCount(string id, string areaCode)
        {
            int cid = int.Parse(id);
            var ret = dbContext.ZbConsultationAnswer.Where(m => m.ConsultationId == cid).Count();
            return ret;
        }

        public override string GetQuestionUser(string userGuid, string areaCode)
        {
            Guid guser = Guid.Empty;
            Guid.TryParse(userGuid, out guser);
            var ret = dbContext.T_Sys_Users.Where(m => m.UserGuid == guser).FirstOrDefault();
            return ret.Name;
        }

        public override void AddConsultationAnswer(DTO.zb_Consultation_Answer submitInfo, string areaCode)
        {
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Entity.ZBDLRY.zb_Consultation_Answer consultation_E = new Entity.ZBDLRY.zb_Consultation_Answer();
                    EntityHelper.ConvertEntity2OtherEntity(submitInfo, consultation_E);
                    consultation_E = dbContext.ZbConsultationAnswer.Add(consultation_E);
                    dbContext.SaveChanges();
                    int cid = Convert.ToInt32(submitInfo.ConsultationId);
                    var consultation = dbContext.ZbConsultation.Where(m => m.ID == cid).FirstOrDefault();
                    consultation.IsAnswer = 2;
                    dbContext.SaveChanges();
                    tran.Commit();

                }
                catch (Exception ex)
                {
                    tran.Rollback();

                }
            }
        }
        #endregion

        public override List<ProgressNode> GetProgressNodes(string classId, string areaCode, string flowCode)
        {
            return Fly.Common.WorkFlow.FlowHelper.GetProgressNodes(classId, areaCode, flowCode);
        }

        /// <summary>
        /// 聊城批量导入企业信息,并生成用户信息
        /// </summary>
        /// <param name="corps"></param>
        /// <param name="areacode"></param>
        /// <returns></returns>
        public override List<ImportCompanyInfo> BatchImportCorpUser(List<ImportCompanyInfo> corpList, string areacode)
        {
            //dbContext.
            if (corpList == null || corpList.Count == 0)
                return null;
            List<ImportCompanyInfo> erroList = new List<ImportCompanyInfo>();
            foreach (var corp in corpList)
            {
                if (dbContext.Corp_CompanyInfos.Where(r => r.OrginazationCode == corp.OrginazationCode && r.IsDel == false).Count() > 0)
                {
                    corp.Description = "企业组织机构编码已存在";
                    erroList.Add(corp);
                    continue;
                }
                #region 入库
                Tb_Corp_Embranchment_Zbdl em = new Tb_Corp_Embranchment_Zbdl();
                DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection;
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    dbContext.Configuration.AutoDetectChangesEnabled = false;
                    int corpClassID = 2501;
                    ////根据市直与县区区分业务流程码
                    OperationResult result = UrbanVerify(corp.AreaCode);
                    if (result.Result)
                    {
                        if (!(Boolean)result.ReturnValue)
                        {
                            corpClassID = 25010;
                        }
                    }

                    //企业表
                    Guid userGuid = Guid.NewGuid();
                    Guid corpGuid = Guid.NewGuid();
                    int roleID = 15;
                    int.TryParse(corp.Type, out roleID);
                    Tb_Corp_CompanyInfo_Zbdl corpMode = new Tb_Corp_CompanyInfo_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity<ImportCompanyInfo, Tb_Corp_CompanyInfo_Zbdl>(corp, corpMode);
                    corpMode.IsDel = false;
                    corpMode.CorpUserGuid = userGuid;
                    corpMode.CorpGuid = Guid.NewGuid();
                    corpMode.classID = corpClassID;
                    dbContext.Corp_CompanyInfos.Add(corpMode);
                    int corpid = dbContext.SaveChanges();

                    //用户表
                    T_Sys_Users_Zbdl userMode = new T_Sys_Users_Zbdl()
                    {
                        UserGuid = userGuid,
                        UserName = corp.OrginazationCode,
                        Name = corp.CorpName,
                        Pwd = "123456",
                        DogID = -1,
                        AreaCode = corp.AreaCode,
                        AreaCodeScope = corp.AreaCode,
                        bGrade = roleID,
                        RoleID = roleID,
                        ClassID = 2000,
                        TreeID = 3336,
                        ZZJGDM = corp.OrginazationCode,
                        RegisterDate = DateTime.Now,
                        LastActiveDate = DateTime.Now,
                        CorpID = corpid
                    };
                    dbContext.T_Sys_Users.Add(userMode);


                    ////添加用户角色。
                    string sRoleId = corp.Type;
                    Entity.Authority.T_Sys_Roles role = dbContext.SysRoles.FirstOrDefault(r => r.Code == sRoleId && r.IsDel == false);
                    if (role != null)
                    {
                        dbContext.SysUserRoles.Add(new Entity.Authority.T_Sys_UserRole()
                        {
                            IsDel = false,
                            IsrtDate = DateTime.Now,
                            IsrtUseID = userGuid,
                            RoleGuid = role.RoleGuid,
                            UserGuid = userGuid
                        });
                    }

                    dbContext.SaveChanges();
                    //添加市场区域信息
                    em.AreaCode = corp.AreaCode.Substring(0, 2);
                    em.IsNative = true;
                    em.CorpGuid = corpGuid;
                    em.CorpUserGuid = userGuid;
                    em.BranchName = corp.CorpName;
                    em.IsrtDate = DateTime.Now;
                    em.Address = corp.Address;
                    em.BranchGid = Guid.NewGuid();
                    dbContext.CorpEmbranchment.Add(em);
                    //添加审核记录
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl model = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = corp.AreaCode.Substring(0, 2),
                        CodeType = corpMode.classID,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = userGuid.ToString(),
                        UpdateTime = DateTime.Now,
                        AppID = 101
                    };
                    baseBll.AddFlowcode(model);
                    //添加日志
                    baseBll.InsertUserLog("企业注册", corpMode.ID.ToString(), corpMode.classID.ToString(), "1");
                    dbContext.SaveChanges();
                    tran.Commit();

                    //订单
                    if ("1" == ConfigurationManager.AppSettings["LCOrder"])
                        OrderGenerate_lc(userGuid, areacode);

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    corp.Description = "入库失败";
                    erroList.Add(corp);
                }

                con.Close();
                #endregion
            }

            return erroList;
        }


        private OperationResult OrderGenerate_lc(Guid CorpGuid, string areacode)
        {
            OperationResult ret = new OperationResult();
            ret.ReturnValue = -9;
            try
            {
                Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.FirstOrDefault(m => m.CorpGuid == CorpGuid);
                ZBDL_Context orderContext = new ZBDL_Context();
                var hasold = orderContext.CAPayInfoSub.Any(m => m.SourceID == corp.ID && m.bCAKind == "E33");
                if (hasold)
                {
                    ret.ReturnValue = -1;
                    ret.Message = "订单已存在";
                    return ret;
                }
                Entity.ZBDLRY.tb_CAPayInfo order = new Entity.ZBDLRY.tb_CAPayInfo();
                order.AreaCode = areacode;  // corp.AreaCode;  ///
                order.bCAStatus = 3;//1：提示  2：线下 3：财务确认 4：制Key
                order.bcorpkind = int.Parse(corp.Type);
                order.caResult = "";
                order.Code = DateTime.Now.ToString("yyMMddHHmmssff") + "02";
                order.CorpUserGuid = corp.CorpUserGuid;
                order.FlowCode = "0,019,029,;4000";
                order.iTitle = corp.CorpName;
                order.KeyGUID = Guid.NewGuid();
                order.LinkPerson = corp.LinkMan1;
                order.mobileTel = "";
                order.officeTel = corp.Tel;
                order.OptDate = DateTime.Now;
                order.postcode = corp.ZipCode;
                order.RegisterDate = DateTime.Now;
                order.RightCode = 1;
                order.SendAddress = corp.Address;
                order.SumPay = 1000;
                order.TransDate = DateTime.Now;
                order.GroupCode = "CA02";
                order.CurrentAreaCode = areacode;


                Entity.ZBDLRY.tb_CAPayInfo_Sub detail = new Entity.ZBDLRY.tb_CAPayInfo_Sub();
                detail.KeyGUID = Guid.NewGuid();
                detail.Remark = "";
                detail.RightCode = 1;
                detail.SourceID = corp.ID;
                detail.SumPay = 1000;
                detail.Title = corp.CorpName;
                detail.bCAKind = "F10";
                detail.bCAStatus = 3;
                detail.bStatus = 1;
                detail.btype = 0;
                detail.FlowCode = "0,019,029,;4000";

                orderContext.CAPayInfo.Add(order);
                orderContext.CAPayInfoSub.Add(detail);
                DbConnection con = ((IObjectContextAdapter)orderContext).ObjectContext.Connection;
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    orderContext.SaveChanges();
                    detail.treeID = order.ID;
                    orderContext.SaveChanges();
                    tran.Commit();

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                }
                ret.ReturnValue = 0;
                con.Close();
            }
            catch (Exception ex)
            {
                ret.ReturnValue = -2;
                ret.Message = ex.Message;
            }
            return ret;
        }

        #region 考核获取企业信息 2014-5-14 毛凯
        public override CompanyBusinessInfoKH GetCompanyBusinessInfoKH(string corpUserGuid, string snapGuid, string areaCode)
        {
            CompanyBusinessInfoKH result = new CompanyBusinessInfoKH();
            if (!string.IsNullOrEmpty(snapGuid))
            {
                ////获取保存的记录
                return null;
            }
            Guid _corpUserGuid = Guid.Empty;
            if (!string.IsNullOrEmpty(corpUserGuid) && Guid.TryParse(corpUserGuid, out _corpUserGuid))
            {
                result.CompanyInfoKH = GetCompanyinfoKH(_corpUserGuid, areaCode);
                ////资金及经营情况
                var corpAttchInfo = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == _corpUserGuid && (o.IsDel == null || o.IsDel == false)).FirstOrDefault();
                if (corpAttchInfo != null)
                {
                    var jsonCapitalBusinessKH = (JsonConvert.DeserializeObject<List<JsonEntity>>(corpAttchInfo.Content1)).FirstOrDefault();
                    if (jsonCapitalBusinessKH != null)
                    {
                        CapitalBusinessKH capitalBusinessKH = JsonConvert.DeserializeObject<CapitalBusinessKH>(jsonCapitalBusinessKH.value.Trim('\"'));
                        result.CapitalBusinessKH = capitalBusinessKH;
                    }
                    var jsonProjectAchieveMentKH = (JsonConvert.DeserializeObject<List<JsonEntity>>(corpAttchInfo.Content2)).FirstOrDefault();
                    if (jsonProjectAchieveMentKH != null)
                    {
                        ProjectAchieveMentKH projectAchieveMentKH = JsonConvert.DeserializeObject<ProjectAchieveMentKH>(jsonProjectAchieveMentKH.value.Trim('\"'));
                        result.ProjectAchieveMentKH = projectAchieveMentKH;
                    }
                }
                return result;
            }
            return null;
        }

        private DTO.CompanyinfoKH GetCompanyinfoKH(Guid corpUserGuid, string areaCode)
        {
            ////企业基本信息
            DTO.CompanyinfoKH companyinfoKH = new CompanyinfoKH();
            BasicBLL basicBll = new BasicBLL();
            var corpInfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpUserGuid && (c.IsDel == null || c.IsDel == false)).FirstOrDefault();
            if (corpInfo == null)
            {
                return null;
            }
            companyinfoKH.ID = corpInfo.ID;
            companyinfoKH.Address = corpInfo.Address;
            companyinfoKH.AreaCode = corpInfo.AreaCode;
            companyinfoKH.AreaCode2 = corpInfo.AreaCode2;
            companyinfoKH.BankAccNo = corpInfo.BankName + corpInfo.BankAccNo;
            companyinfoKH.BussinessArea = corpInfo.BussinessArea;
            companyinfoKH.BussinessNum = corpInfo.BussinessNum;
            companyinfoKH.classID = corpInfo.classID;
            companyinfoKH.CorpGuid = corpInfo.CorpGuid;
            companyinfoKH.CorpName = corpInfo.CorpName;
            companyinfoKH.CorpType = corpInfo.CorpType;
            var corpTypeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicBll.GetDictionary("CorpType", "", areaCode));
            if (corpInfo.CorpType.HasValue && corpTypeDic.ContainsKey(corpInfo.CorpType.ToString()))
            {
                companyinfoKH.CorpTypeTitle = corpTypeDic[corpInfo.CorpType.ToString()];
            }
            companyinfoKH.CorpUserGuid = corpInfo.CorpUserGuid;
            companyinfoKH.FoundTime = corpInfo.FoundTime;
            companyinfoKH.OrginazationCode = corpInfo.OrginazationCode;
            companyinfoKH.RegisterMoney = corpInfo.RegisterMoney;
            companyinfoKH.ZipCode = corpInfo.ZipCode;

            ////主项资质
            var mainQuality = dbContext.Corp_CompanyQualities.Where(q => q.CorpUserGuid == corpUserGuid && q.IsMain == true && (q.IsDel == null || q.IsDel == false)).FirstOrDefault();
            if (mainQuality != null)
            {
                companyinfoKH.MainQualityEndDate = mainQuality.zzzEndDate.HasValue ? mainQuality.zzzEndDate.Value.ToShortDateString() : "";
                companyinfoKH.MainQualityGrade = mainQuality.GradeName;
                companyinfoKH.MainQualityGuid = mainQuality.QualityGuid;
                companyinfoKH.MainQualityTitle = mainQuality.DetailName;
                companyinfoKH.MainQualityCode = mainQuality.QualityCode;
            }

            ////法人
            var postDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicBll.GetDictionary("post", "", areaCode));
            string frTypeFlag = "3";
            var managerFr = dbContext.Emp_Manager.Where(m => m.CorpGuid == corpUserGuid && m.TypeFlag.Contains(frTypeFlag) && (m.IsDel == null || m.IsDel == false)).FirstOrDefault();
            if (managerFr != null)
            {
                companyinfoKH.ManagerFrName = managerFr.Name;
                companyinfoKH.ManagerFrTel = managerFr.Tel;
                var managerFrPost = dbContext.Emp_Post.Where(p => p.EmpGuid == managerFr.EmpGuid && (p.IsDel == null || p.IsDel == false)).FirstOrDefault();
                if (managerFrPost != null)
                {
                    string frPostTitle = postDic.ContainsKey(managerFrPost.Post_psZG) ? postDic[managerFrPost.Post_psZG] : "";
                    frPostTitle += postDic.ContainsKey(managerFrPost.Post_psZGCode) ? "-" + postDic[managerFrPost.Post_psZGCode] : "";
                    companyinfoKH.ManagerFrZhiCheng = frPostTitle;
                }
            }

            ////技术负责人
            string jsFzrTypeFlag = "5";
            var managerJsFzr = dbContext.Emp_Manager.Where(m => m.CorpGuid == corpUserGuid && m.TypeFlag.Contains(jsFzrTypeFlag) && (m.IsDel == null || m.IsDel == false)).FirstOrDefault();
            if (managerJsFzr != null)
            {
                companyinfoKH.ManagerJsFzrName = managerJsFzr.Name;
                companyinfoKH.ManagerJsFzrTel = managerJsFzr.Tel;
                var managerJsFzrPost = dbContext.Emp_Post.Where(p => p.EmpGuid == managerJsFzr.EmpGuid && (p.IsDel == null || p.IsDel == false)).FirstOrDefault();
                if (managerJsFzrPost != null)
                {
                    string frPostTitle = postDic.ContainsKey(managerJsFzrPost.Post_psZG) ? postDic[managerJsFzrPost.Post_psZG] : "";
                    frPostTitle += postDic.ContainsKey(managerJsFzrPost.Post_psZGCode) ? "-" + postDic[managerJsFzrPost.Post_psZGCode] : "";
                    companyinfoKH.ManagerFrZhiCheng = frPostTitle;
                }
            }
            ////实有人员数量 调用人员服务超时，直接查询
            var managerCount = dbContext.ManagerInfoFlow
                .Where(o => o.CorpGuid == corpUserGuid && (o.IsDel == null || o.IsDel == false)
                    && o.FlowAreaCode.StartsWith(areaCode) && o.RealFlowCode.StartsWith("1"))
                    .Select(o => o.EmpGuid).Distinct().Count();
            companyinfoKH.ManagerCount = managerCount;
            return companyinfoKH;
        }
        #endregion

        #region 考核企业附属信息 编辑 2014-5-15 毛凯
        public override OperationResult CompanyAttchInfoKHEdit(
            string corpUserGuid,
            string capitalBusinessKH,
            string projectAchieveMentKH,
            string areaCode)
        {
            OperationResult result = new OperationResult();
            try
            {
                if (string.IsNullOrEmpty(capitalBusinessKH) || string.IsNullOrEmpty(projectAchieveMentKH))
                {
                    result.Result = false;
                    result.Message = "未检测到需要编辑的信息";
                }
                Guid _corpUserGuid = Guid.Empty;
                if (Guid.TryParse(corpUserGuid, out _corpUserGuid))
                {
                    var corpAttachInfo = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == _corpUserGuid && (o.IsDel == null || o.IsDel == false)).FirstOrDefault();
                    if (corpAttachInfo == null)
                    {
                        ////添加
                        Tb_Corp_AttachInfo_Zbdl newCorpAttachInfo = new Tb_Corp_AttachInfo_Zbdl();
                        newCorpAttachInfo.CorpUserGuid = _corpUserGuid;
                        newCorpAttachInfo.Content1 = capitalBusinessKH;
                        newCorpAttachInfo.Content2 = projectAchieveMentKH;
                        newCorpAttachInfo.IsrtDate = DateTime.Now;
                        newCorpAttachInfo.IsDel = false;
                        dbContext.CorpAttachInfo.Add(newCorpAttachInfo);
                        dbContext.SaveChanges();

                    }
                    else
                    {
                        ////修改
                        corpAttachInfo.Content1 = capitalBusinessKH;
                        corpAttachInfo.Content2 = projectAchieveMentKH;
                        corpAttachInfo.IsrtDate = DateTime.Now;
                        dbContext.SaveChanges();
                    }
                    result.Result = true;
                    result.Message = "操作成功";
                }
                else
                {
                    result.Result = false;
                    result.Message = "企业唯一标识错误";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }
            return result;
        }
        #endregion

        #region  查询企业资质
        public override IList<CompanyInfo> GetCorpLists(IList<QueryCompanyInfoCondition> queryCondition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;

            var query = from company in dbCompanies
                        join user in dbUsers
                        on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                            {
                                CorpUserGuid = company.CorpUserGuid,
                                IsMain = (bool?)true,
                                IsDel = (bool?)false
                            } equals new
                            {
                                CorpUserGuid = qualities.CorpUserGuid,
                                IsMain = qualities.IsMain,
                                IsDel = qualities.IsDel
                            }
                        into cq
                        from cq0 in cq.DefaultIfEmpty()
                        select new CompanyInfo
                        {
                            ID = company.ID,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            //  FlowCode = company.RealFlowCode,
                            QualityCode = cq0.QualityCode,
                            DetailName = cq0.DetailName,
                            GradeName = cq0.GradeName,
                            GradeCode = cq0.GradeCode,
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            count = query.Distinct().ToList().Count;
            if (pageSize == 0)
            {
                return query.Distinct().ToList();
            }
            else
            {
                return query.Distinct().ToList().OrderByDescending(c => c.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }

        public override string GetCorpKind(string corpkind, string areaCode)
        {
            // string areacode = ConfigurationManager.AppSettings["Area"].ToString().Substring(0, 2);
            List<tb_Corp_CorpKind_Zbdl> corpkindlist = new List<tb_Corp_CorpKind_Zbdl>();
            switch (corpkind)
            {
                case "31"://预制构件企业
                case "30"://预拌混凝土企业 
                case "90"://检测机构 
                    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 90).ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "55"://代建单位    
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1055").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "15"://施工总包 
                case "17"://外地入青企业
                case "7330"://市政施工总包
                    corpkindlist = dbContext.CorpKind.Where(c => (c.Kind == 1 || c.Kind == 2 || c.Kind == 3) && c.ClassKind == "1000").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "16"://专业承包
                    //if (areacode != "09")
                    //{
                    //    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 2 && c.ClassKind == "1000").ToList<tb_Corp_CorpKind_Zbdl>();
                    //}
                    //else
                    //{
                    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 2 && c.ClassKind == "3000").ToList<tb_Corp_CorpKind_Zbdl>();
                    // }
                    break;
                case "43"://劳务
                    corpkindlist = dbContext.CorpKind.Where(c => c.Kind == 3 && c.ClassKind == "1000").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "42"://监理
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1021").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "45"://建设单位            
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1045").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "46"://造价咨询单位
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1046").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "47"://勘察设计单位
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1047").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "105"://招标代理资质等级
                    corpkindlist = dbContext.CorpKind.Where(c => c.ClassKind == "1105").ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
                case "":
                    corpkindlist = dbContext.CorpKind.Where(c => c.ID > 0).ToList<tb_Corp_CorpKind_Zbdl>();
                    break;
            }
            return JsonConvert.SerializeObject(corpkindlist);
        }
        #endregion

        public override DTO.OperationResult IsUrban(string userGuid)
        {
            DTO.OperationResult result = new OperationResult();
            result.Result = false;
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(userGuid, out guid))
            {
                result.Result = false;
                result.Message = "参数不正确！";
                return result;
            }
            var user = dbContext.T_Sys_Users.FirstOrDefault(o => o.UserGuid == guid);
            if (user == null)
            {
                result.Message = "用户不存在";
                return result;
            }
            result = UrbanVerify(user.AreaCode);
            return result;
        }

        private DTO.OperationResult UrbanVerify(string areaCode)
        {
            DTO.OperationResult result = new OperationResult();
            result.Result = false;
            if (String.IsNullOrEmpty(areaCode))
            {
                result.Message = "地区参数不正确";
                return result;
            }
            string area = ConfigurationManager.AppSettings["UrbanDefine"];
            if (string.IsNullOrEmpty(area))
            {
                result.Message = "读取配置地区失败";
                return result;
            }
            if (!String.IsNullOrEmpty(area))
            {
                List<string> areaList = new List<string>();
                areaList.Add(area);
                if (area.Length > 2)
                {
                    area = area.Substring(0, 2);
                    areaList.Add(area);
                }
                if (areaList.Contains(areaCode))
                {
                    result.Message = "验证地区成功";
                    result.Result = true;
                    result.ReturnValue = true;
                }
                else
                {
                    ////聊城外地企业归属到市直
                    if(areaCode.Length>=2&&(!areaCode.StartsWith("14")))
                    {
                        result.Message = "验证地区成功";
                        result.Result = true;
                        result.ReturnValue = true;
                        return result;
                    }
                    result.Message = "验证地区成功";
                    result.Result = true;
                    result.ReturnValue = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业自有或租赁的主要机械设备列表查询
        /// </summary>       
        public override List<DTO.tb_corp_MachineInfo> GetCorpMachineInfoList(int pageIndex, int pageSize, out int count, Guid corpGuid, bool? isOwn, string areaCode)
        {
            count = 0;
            List<DTO.tb_corp_MachineInfo> list = new List<DTO.tb_corp_MachineInfo>();
            var rst = dbContext.CorpMachines.Where(r => r.CorpUserGuid == corpGuid && r.IsDel == false);
            if (isOwn != null)
            {
                rst = rst.Where(r => r.IsOwn == isOwn);
            }
            var machines = rst.ToList();
            if (machines != null)
            {
                count = machines.Count;
                machines = machines.Skip(pageIndex * pageSize).Take(pageSize).ToList();
                if (machines != null && machines.Count > 0)
                {
                    foreach (RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo m in machines)
                    {
                        DTO.tb_corp_MachineInfo mac = new DTO.tb_corp_MachineInfo();
                        EntityHelper.ConvertEntity2OtherEntity<RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo, DTO.tb_corp_MachineInfo>(m, mac);
                        if (mac != null & mac.ID > 0)
                            list.Add(mac);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 企业自有或租赁的主要机械设备查询
        /// </summary>  
        public override DTO.tb_corp_MachineInfo GetCorpMachineInfoByID(Guid corpGuid, int id, string areaCode)
        {
            DTO.tb_corp_MachineInfo machine = new DTO.tb_corp_MachineInfo();
            var rst = dbContext.CorpMachines.Where(r => r.ID == id && r.IsDel == false).FirstOrDefault();

            if (rst != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo, DTO.tb_corp_MachineInfo>(rst, machine);
            }
            return machine;
        }

        /// <summary>
        /// 添加企业自有或租赁的主要机械设备
        /// </summary>       
        public override bool AddCorpMachineInfo(DTO.tb_corp_MachineInfo model, string areaCode)
        {
            bool rst = false;
            //RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo model=dbContext.CorpMachines.Where(r=>r.IsDel==false &&r.CorpUserGuid

            if (model != null)
            {
                RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo entity = new Entity.ZBDLRY.tb_corp_MachineInfo();
                EntityHelper.ConvertEntity2OtherEntity<DTO.tb_corp_MachineInfo, RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo>(model, entity);
                dbContext.CorpMachines.Add(entity);
                dbContext.SaveChanges();
                rst = true;
            }
            return rst;
        }

        /// <summary>
        /// 逻辑删除企业自有或租赁的主要机械设备列表查询
        /// </summary>       
        public override bool DelCorpMachineInfo(int id, string areaCode)
        {
            bool rst = true;
            try
            {
                RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo entity = null;
                entity = dbContext.CorpMachines.Where(r => r.IsDel == false && r.ID == id).FirstOrDefault();
                if (entity != null && entity.ID > 0)
                {
                    entity.IsDel = true;
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                rst = false;
            }

            return rst;
        }
        /// <summary>
        /// 修改企业自有或租赁的主要机械设备
        /// </summary>       
        public override bool UpdateCorpMachineInfo(DTO.tb_corp_MachineInfo model, string areaCode)
        {
            bool rst = false;
            RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo entity = dbContext.CorpMachines.Where(r => r.IsDel == false && r.ID == model.ID).FirstOrDefault();

            if (entity != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<DTO.tb_corp_MachineInfo, RN.ERP.Entity.ZBDLRY.tb_corp_MachineInfo>(model, entity);
                dbContext.SaveChanges();
                rst = true;
            }
            return rst;
        }


        /// <summary>
        /// 企业企业财务经营状况列表查询
        /// </summary>       
        public override List<DTO.tb_corp_FinancialInfo> GetCorpFinancialInfoList(
            string corpName, 
            int pageIndex, 
            int pageSize,
            Guid corpGuid, 
            int? currentYear, 
            string areaCode,
            out int count)
        {
            count = 0;
            List<DTO.tb_corp_FinancialInfo> list = new List<DTO.tb_corp_FinancialInfo>();
            if (areaCode.Equals("1408"))
            {
                areaCode = "14";
            }

            var query = from finacial in dbContext.CorpFinancials
                        join user in dbContext.T_Sys_Users 
                        on finacial.CorpUserGuid equals user.UserGuid
                        where finacial.IsDel == false && user.AreaCode.Contains(areaCode)
                        select finacial ; 
            if (currentYear != null)
            {
                query = query.Where(r => r.CurrentYear == currentYear);
            }
            if (corpGuid != null && corpGuid != Guid.Empty)
            {
                query = query.Where(r => r.CorpUserGuid == corpGuid);
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                query = query.Where(r => r.CorpName.Contains(corpName));
            }
            
            var financials = query.ToList();
            if (financials != null)
            {
                count = financials.Count;
                financials = financials.Skip(pageIndex * pageSize).Take(pageSize).ToList();
                if (financials != null && financials.Count > 0)
                {
                    foreach (RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo f in financials)
                    {
                        DTO.tb_corp_FinancialInfo model = new DTO.tb_corp_FinancialInfo();
                        EntityHelper.ConvertEntity2OtherEntity<RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo, DTO.tb_corp_FinancialInfo>(f, model);
                        if (model != null & model.ID > 0)
                            list.Add(model);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 企业企业财务经营状况查询
        /// </summary> 
        public override DTO.tb_corp_FinancialInfo GetCorpFinancialInfoByID(Guid corpGuid, int id, string areaCode)
        {
            DTO.tb_corp_FinancialInfo finan = new DTO.tb_corp_FinancialInfo();
            var rst = dbContext.CorpFinancials.Where(r => r.ID == id && r.IsDel == false).FirstOrDefault();

            if (rst != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo, DTO.tb_corp_FinancialInfo>(rst, finan);
            }
            return finan;
        }

        public override DTO.tb_corp_FinancialInfo GetCorpFinancialInfoByYear(Guid corpGuid, int? currentYear, string areaCode)
        {
            DTO.tb_corp_FinancialInfo finan = new DTO.tb_corp_FinancialInfo();
            var rst = dbContext.CorpFinancials.Where(r => r.CurrentYear == currentYear && r.CorpUserGuid == corpGuid && r.IsDel == false).FirstOrDefault();

            if (rst != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo, DTO.tb_corp_FinancialInfo>(rst, finan);
            }
            return finan;
        }


        /// <summary>
        /// 添加企业财务经营状况
        /// </summary>       
        public override bool AddCorpFinancialInfo(DTO.tb_corp_FinancialInfo model, string areaCode)
        {
            bool rst = false;

            if (model != null)
            {
                RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo entity = new Entity.ZBDLRY.tb_corp_FinancialInfo();
                EntityHelper.ConvertEntity2OtherEntity<DTO.tb_corp_FinancialInfo, RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo>(model, entity);
                dbContext.CorpFinancials.Add(entity);
                dbContext.SaveChanges();
                rst = true;
            }
            return rst;
        }




        /// <summary>
        /// 逻辑企业财务经营状况
        /// </summary>       
        public override bool DelCorpFinancialInfo(int id, string areaCode)
        {
            bool rst = true;
            try
            {
                RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo entity = null;
                entity = dbContext.CorpFinancials.Where(r => r.IsDel == false && r.ID == id).FirstOrDefault();
                if (entity != null && entity.ID > 0)
                {
                    entity.IsDel = true;
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                rst = false;
            }

            return rst;
        }
        /// <summary>
        /// 修改企业财务经营状况
        /// </summary>       
        public override bool UpdateCorpFinancialInfo(DTO.tb_corp_FinancialInfo model, string areaCode)
        {
            bool rst = false;
            RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo entity = dbContext.CorpFinancials.Where(r => r.IsDel == false && r.ID == model.ID).FirstOrDefault();

            if (entity != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<DTO.tb_corp_FinancialInfo, RN.ERP.Entity.ZBDLRY.tb_corp_FinancialInfo>(model, entity);
                dbContext.SaveChanges();
                rst = true;
            }
            return rst;
        }

        #region 企业注册审核(聊城)
        public override List<CompanyInfo> GetCorpRegListLC(out int count, int pageNum, int pageSize, List<QueryCompanyInfoCondition> condition, string areaCode)
        {
            var dbCompanies = dbContext.CompanyRegFlowLC;
            var dbUsers = dbContext.T_Sys_Users;
            var dbCMFlow = dbContext.CMFlow;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        where company.IsDel == false
                        select new CompanyInfo
                        {
                            #region 封装实体
                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            OrginazationCode = company.OrginazationCode,
                            GetDate = user.RegisterDate,
                            FlowCodeType = company.FlowCodeType
                            #endregion
                        };

            if (condition != null && condition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(condition);
            }
            count = query.Count();
            query = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize);
            var result = query.ToList();
            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                                        areaCode,
                                        item.classID.ToString(),
                                        item.FlowCode);
                }
                catch
                {

                }
            }
            return result;
        }
        #endregion


        /// <summary>
        /// 修改企业类型
        /// </summary>      
        public override OperationResult UpdateCorpType(string corpUserGuid, int roleid, int classid, string areaCode, string OptManGuid, string OptManName)
        {
            OperationResult rst = new OperationResult { Result = false, Message = "指定修改企业不存在" };
            Guid userGuid = new Guid();
            Guid.TryParse(corpUserGuid, out userGuid);
            if (userGuid == new Guid())
            {
                return rst;
            }
            //EnterpriseDALWh
            T_Sys_Users_Zbdl user = dbContext.T_Sys_Users.Where(r => r.UserGuid == userGuid).FirstOrDefault();
            if (user != null)
            {
                Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(r => r.CorpUserGuid == userGuid &&r.IsDel==false).FirstOrDefault();
                if (corp == null)
                    return rst;
                bool isShiZhi = false;
                if (corp.AreaCode == "14" || corp.AreaCode == System.Configuration.ConfigurationManager.AppSettings["UrbanDefine"])
                {
                    isShiZhi = true;
                }
                 classid = this.GetClassIDbyLC(classid, 1, isShiZhi);
                if (corp.classID != classid)
                {
                    try
                    {
                        int? oldCorpClassID = corp.classID;
                        corp.classID = classid; //修改企业classid
                        //修改企业审核类型
                        this.EditFlowCodeCodeType(classid, userGuid.ToString());
                        //修改企业下人员classid及审核codetype
                        int managerClassID = this.GetClassIDbyLC(classid, 2, isShiZhi);
                        List<tb_Emp_Manager_Zbdl> mans = dbContext.Emp_Manager.Where(r => r.CorpGuid == userGuid && r.IsDel == false && (r.ClassId == null || r.ClassId != managerClassID)).ToList();
                        if (mans != null && mans.Count > 0)
                        {
                            int titleClassID = this.GetClassIDbyLC(classid, 3, isShiZhi);
                            foreach (var m in mans)
                            {
                                m.ClassId = managerClassID;
                                dbContext.Entry<tb_Emp_Manager_Zbdl>(m).State = EntityState.Modified;
                                this.EditFlowCodeCodeType(managerClassID, m.EmpGuid.ToString());

                                //修改人证的classid
                                List<Tb_Emp_TitleDetails_Zbdl> titles = dbContext.Emp_Qualities.Where(r => r.EmpGuid == m.EmpGuid && r.IsDel == false && (r.ClassID == null || r.ClassID != titleClassID)).ToList();
                                if (titles != null && titles.Count > 0)
                                {
                                    foreach (var t in titles)
                                    {
                                        t.ClassID = titleClassID;
                                        dbContext.Entry<Tb_Emp_TitleDetails_Zbdl>(t).State = EntityState.Modified;
                                    }
                                }

                            }
                            dbContext.SaveChanges();
                        }
                        dbContext.SaveChanges();
                        //记录日志
                        baseBll.InsertUserLog("企业类型修改", userGuid.ToString(), classid.ToString(), "2");
                        rst = new OperationResult { Result = true, Message = "修改成功" };
                    }
                    catch (Exception ex)
                    {
                        rst = new OperationResult { Result = true, Message = "修改失败" };
                    }
                }

            }
            return rst;
        }

        private void EditFlowCodeCodeType(int classid, string userGuid)
        {
            List<Tb_FlowCode_Zbdl> corpFlows = dbContext.FlowCodes.Where(r => r.ObjectId == userGuid && r.IsDel == false).ToList();
            if (corpFlows != null && corpFlows.Count > 0)
            {
                foreach (var cf in corpFlows)
                {
                    cf.CodeType = classid;
                    dbContext.Entry<Tb_FlowCode_Zbdl>(cf).State = EntityState.Modified;
                }
                dbContext.SaveChanges();
            }
        }
        /// <summary>
        /// 修改企业管理地
        /// </summary>
        public override OperationResult UpdateCorpManageZone(string corpUserGuid, string areaCode, string OptManGuid, string OptManName)
        {
            OperationResult rst = new OperationResult { Result = false, Message = "指定修改企业不存在" };
            Guid userGuid = new Guid();
            Guid.TryParse(corpUserGuid, out userGuid);
            if (userGuid == new Guid())
            {
                return rst;
            }
           
            T_Sys_Users_Zbdl user = dbContext.T_Sys_Users.Where(r => r.UserGuid == userGuid).FirstOrDefault();

            if (user != null&&user.AreaCode!=areaCode)
            {
                try
                {
                    user.AreaCode = areaCode;
                    Tb_Corp_CompanyInfo_Zbdl corp = dbContext.Corp_CompanyInfos.Where(r => r.CorpUserGuid == userGuid && r.IsDel == false).FirstOrDefault();
                    if (corp == null)
                        return rst;

                    bool isShiZhi = false;
                    if (corp.AreaCode == "14" || corp.AreaCode == System.Configuration.ConfigurationManager.AppSettings["UrbanDefine"])
                    {
                        isShiZhi = true;
                    }
                    bool isShiZhiAfter = false;
                    if (corp.AreaCode == "14" || areaCode == System.Configuration.ConfigurationManager.AppSettings["UrbanDefine"])
                    {
                        isShiZhiAfter = true;
                    }
                    corp.AreaCode = areaCode;
                    int newClassID = corp.classID ?? 2501;
                    dbContext.SaveChanges();
                    if (isShiZhi != isShiZhiAfter)
                    {

                        ///由市直改为非市直
                        if (isShiZhi && !isShiZhiAfter)
                        {
                            UpdateCorpType(userGuid.ToString(), 15, newClassID, areaCode, "", "");
                        }
                        else
                        { //由非市直改为市直  需修改classid
                            UpdateCorpType(userGuid.ToString(), 15, newClassID - 10, areaCode, "", "");

                        }
                    }
                    //记录日志
                    baseBll.InsertUserLog("企业管理地修改" + areaCode, userGuid.ToString(), newClassID.ToString(), "2");
                    rst = new OperationResult { Result = true, Message = "修改成功" };
                }
                catch (Exception ex)
                {
                    rst = new OperationResult { Result = false, Message = "修改失败" };
                }
                

            }
            return rst;
        }


        /// <summary>
        /// 获取聊城企业信息
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <param name="corpName"></param>
        /// <param name="classid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<DTO.CompanyInfo> GetCorpListLC(out int count, int pageNum, int pageSize, string corpName, int classid, string areaCode)
        {
            count = 0;
            List<DTO.CompanyInfo> rst=new List<CompanyInfo>();
            
           var query=from  c in  dbContext.CompanyInfoFlow select c;
            if(!string.IsNullOrEmpty(corpName))
            {
                query = query.Where(r => r.CorpName.Contains(corpName));
            }
            if (classid>0)
            {
                query = query.Where(r => r.classID == classid * 10 || r.classID == classid);
            }
            if (!string.IsNullOrEmpty(areaCode))
            {
                query = query.Where(r => r.AreaCode.Contains(areaCode));
            }

            List<V_EF_CompanyInfo> list = query.ToList();
            if (list != null && list.Count > 0)
            {
                count = list.Count;
                list = list.Skip(pageSize * (pageNum-1)).Take(pageSize).ToList();
                if (list != null)
                {
                    list.ForEach(r => r.FlowCode = r.RealFlowCode);
                    DTO.CompanyInfo model = null;
                    foreach (var c in list)
                    {
                        model = new DTO.CompanyInfo();
                        EntityHelper.ConvertEntity2OtherEntity<V_EF_CompanyInfo, DTO.CompanyInfo>(c, model);
                        if (model != null && model.ID > 0)
                        {
                            rst.Add(model);
                        }
                    }
                    if (rst != null && rst.Count > 0)
                    {
                        string areaCode_Config=System.Configuration.ConfigurationManager.AppSettings["area"];
                        List<a_AreaSubInfo_Zbdl> areas = dbContext.AreaSubInfo.Where(r => r.Code == areaCode_Config).ToList();
                        foreach (var en in rst)
                        {
                            en.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(en.AreaCode, en.classID.ToString(), en.FlowCode);
                           a_AreaSubInfo_Zbdl area= areas.Where(r=>r.SortCode==en.AreaCode).FirstOrDefault();
                            en.AreaName = area==null?"":area.Title;
                            try
                            {
                                en.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                                                    areaCode_Config,
                                                    en.classID.ToString(),
                                                    en.FlowCode);
                            }
                            catch
                            {

                            }
                        }
                    }
                }  
                      
            }
          
            return rst;
        }
        /// <summary>
        /// 聊城获取classid
        /// </summary>
        /// <param name="corpClassID">预设市直企业对应的ClassID</param>
        /// <param name="type">1:企业，2：人员 3：证书</param>
        /// <param name="isShiZhi"></param>
        /// <returns></returns>
        private int GetClassIDbyLC(int corpClassID,int type,bool isShiZhi)
        {
            int classid = 2501;
           
            switch (type)
            {
                case 1:
                    if (!isShiZhi)
                    {
                        corpClassID = corpClassID * 10;
                    }
                    classid= corpClassID;
                    break;
                case 2:
                    classid = corpClassID + 10;
                    break;
                case 3:
                     classid = (corpClassID + 10)+100;
                    break;

            }
            return classid;
        }

        public override IList<CompanyInfo> GetCorpListByGroupID(
        IList<QueryCompanyInfoCondition> queryCondition, 
        int pageSize, 
        int pageNum, 
        string areaCondition,
        int groupId,
        out int cnt)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            var dbTitles=dbContext.Emp_Qualities;
            var dbEmp=dbContext.Emp_Manager;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == areaCondition
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            AppID = company.AppID
                            #endregion
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            var result = new List<DTO.CompanyInfo>();
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            cnt = query.Count();
            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }
            foreach (var item in result)
            {
                item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                    areaCondition,
                    item.classID.ToString(),
                    item.FlowCode);
                item.bISO9000 = 0;
                if (groupId != -1)
                {
                    var certs = from titles in dbTitles
                                join emps in dbEmp on new
                                {
                                    EmpGuid = titles.EmpGuid,
                                    IsDel = titles.IsDel
                                }
                                equals new
                                {
                                    EmpGuid = (Guid?)emps.EmpGuid,
                                    IsDel = (bool?)false
                                }
                                where (titles.IsDel == false || titles.IsDel == null)
                                && titles.GroupTreeID == groupId && titles.FlowCode != null 
                                && titles.FlowCode.Contains("019")
                                && (emps.IsDel == false || emps.IsDel == null)
                                && emps.CorpGuid == item.CorpUserGuid
                                select titles;
                    int? num = certs.ToList().GroupBy(o => o.GroupTreeID).Select(k => k.Count()).FirstOrDefault();
                    item.bISO9000 = num ?? 0;
                }
            }
            return result;
        }

        public override IList<CompanyInfo> GetCorpPostInfoList(
        IList<QueryCompanyInfoCondition> queryCondition,
        int pageSize,
        int pageNum,
        string areaCondition,
        int groupId,
        out int cnt)
        {
            var dbCompanies = dbContext.CompanyInfoFlow;
            var dbMainQualities = dbContext.Corp_CompanyQualities;
            var dbUsers = dbContext.T_Sys_Users;
            //var dbTitles = dbContext.Emp_Qualities;
            var dbPost = dbContext.Emp_Post;
            var dbEmp = dbContext.Emp_Manager;
            var query = from company in dbCompanies
                        join user in dbUsers on company.CorpUserGuid equals user.UserGuid
                        join qualities in dbMainQualities on new
                        {
                            CorpUserGuid = company.CorpUserGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            CorpUserGuid = qualities.CorpUserGuid,
                            IsMain = qualities.IsMain,
                            IsDel = qualities.IsDel
                        } into jQualities
                        from quality in jQualities.DefaultIfEmpty()
                        where company.FlowAreaCode == areaCondition
                        select new CompanyInfo
                        {
                            #region 封装实体

                            ID = company.ID,
                            classID = company.classID,
                            Dogid = company.dogid,
                            CorpGuid = company.CorpGuid,
                            CorpUserGuid = company.CorpUserGuid,
                            CorpName = company.CorpName,
                            RoleId = user.RoleID,
                            AreaCode = company.AreaCode,
                            AreaCode2 = company.AreaCode2,
                            Address = company.Address,
                            ZipCode = company.ZipCode,
                            NetAddress = company.NetAddress,
                            Email = company.Email,
                            LinkMan1 = company.LinkMan1,
                            Tel1 = company.Tel1,
                            Linkman = company.Linkman,
                            Tel = company.Tel,
                            Fax = company.Fax,
                            SecurityTitleGetDate = company.SecurityTitleGetDate,
                            SecurityCode = company.SecurityCode,
                            Introduction = company.Introduction,
                            EndTime = company.EndTime,
                            PassNum = company.PassNum,
                            QualificationNum = company.QualificationNum,
                            QualificationLevel = company.QualificationLevel,
                            BussinessNum = company.BussinessNum,
                            FoundTime = company.FoundTime,
                            BussinessArea = company.BussinessArea,
                            Type = company.Type,
                            FlowCode = company.RealFlowCode,
                            RegisterMoney = company.RegisterMoney,
                            bISO14000 = company.bISO14000,
                            bISO9000 = company.bISO9000,
                            bISO9001 = company.bISO9001,
                            bOHSMS18000 = company.bOHSMS18000,
                            QualityState = company.QualityState,
                            bCanBid = company.bCanBid,
                            QualityGuid = quality.QualityGuid,
                            DetailName = quality.DetailName,
                            KindID = quality.KindID,
                            GradeName = quality.GradeName,
                            GradeCode = quality.GradeCode,
                            GetDate = quality.GetDate,
                            OrginazationCode = company.OrginazationCode,
                            AppID = company.AppID,
                            NoCard = 0
                            #endregion
                        };
            if (queryCondition != null && queryCondition.Count > 0)
            {
                query = query.BuildCondition<CompanyInfo>(queryCondition);
            }
            var result = new List<DTO.CompanyInfo>();
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            cnt = query.Count();
            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }
            foreach (var item in result)
            {
                item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                    areaCondition,
                    item.classID.ToString(),
                    item.FlowCode);
                item.bISO9000 = 0;

                    var certs = from posts in dbPost
                                join emps in dbEmp on new
                                {
                                    EmpGuid = (Guid?)posts.EmpGuid,
                                    IsDel = posts.IsDel
                                }
                                equals new
                                {
                                    EmpGuid = (Guid?)emps.EmpGuid,
                                    IsDel = (bool?)false
                                }
                                where (posts.IsDel == false || posts.IsDel == null)
                                && (emps.IsDel == false || emps.IsDel == null)
                                && emps.CorpGuid == item.CorpUserGuid
                                && posts.FlowCode != null
                                select posts;
                    int? num = certs.ToList().Count();
                    item.bISO9000 = num ?? 0;

            }
            return result;
        }

        #region 企业组织机构代码修改(聊城)
        /// <summary>
        /// 企业获取组织机构代码信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="codeType"></param>
        /// <param name="appID"></param>
        /// <returns></returns>
        public override DTO.Tb_FlowCode GetCorpOrgByCorpUserGuid(string corpUserGuid, string areaCode, int codeType, int appID)
        {
            DTO.Tb_FlowCode flowCodeDTO = new Tb_FlowCode();

            Tb_FlowCode_Zbdl flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == codeType
                    && f.AreaCode == areaCode && (f.IsDel == null || f.IsDel == false) && f.AppID == appID).FirstOrDefault();
            EntityHelper.ConvertEntity2OtherEntity(flowCode, flowCodeDTO);

            return flowCodeDTO;
        }
        /// <summary>
        /// 企业上报申请修改组织机构代码
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="codeType"></param>
        /// <param name="appID"></param>
        /// <param name="optType"></param>
        /// <returns></returns>
        public override OperationResult CorpOrgPost(string orgCode, string corpUserGuid, string orgGuid, string areaCode, int codeType, int appID, int optType)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid userGuid = new Guid();
            Guid.TryParse(corpUserGuid, out userGuid);

            bool isValid = CheckOrginazationCode(orgCode);
            if (!isValid)
            {
                result.Result = false;
                result.Message = "组织机构代码有误！";
                return result;
            }

            T_Sys_Users_Zbdl user = dbContext.T_Sys_Users.Where(m => m.UserGuid == userGuid).FirstOrDefault();
            if(user == null)
            {
                result.Result = false;
                result.Message = "用户表不存在该企业！";
                return result;
            }

            var companyinfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == userGuid).FirstOrDefault();
            var corpInfoWithSameOrgCode = dbContext.Corp_CompanyInfos.Where(c => c.OrginazationCode == orgCode && c.classID == companyinfo.classID && c.CorpUserGuid != userGuid).FirstOrDefault();
            if (corpInfoWithSameOrgCode != null)
            {
                result.Message = "组织机构代码已被企业【" + corpInfoWithSameOrgCode.CorpName + "】注册，请检查！";
                result.Result = false;
                return result;
            }

            string description = "{ \"CorpName\" : \"" + user.Name + "\", \"CorpUserGuid\" : \"" + corpUserGuid
                + "\", \"OrgCode\" : \"" + orgCode + "\", \"PostDate\" : \"" + DateTime.Now.ToString() + "\", \"OrgGuid\" : \"" + orgGuid + "\" }";

            try
            {
                Tb_FlowCode_Zbdl flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == codeType
                    && f.AreaCode == areaCode && (f.IsDel == null || f.IsDel == false) && f.AppID == appID).FirstOrDefault();
                
                if (flowCode == null)
                {
                    flowCode = new Tb_FlowCode_Zbdl();
                    flowCode.ObjectId = corpUserGuid;
                    flowCode.AreaCode = areaCode;
                    flowCode.RoleId = "15";
                    flowCode.Description = description;
                    flowCode.CodeType = codeType;
                    flowCode.FlowCode = "0,019";
                    flowCode.UpdateTime = DateTime.Now;
                    flowCode.IsDel = false;
                    flowCode.AppID = appID;
                    dbContext.FlowCodes.Add(flowCode);
                }
                else
                {
                    if (flowCode.FlowCode.StartsWith("1"))////已经变更过的企业再次变更，需将上次的逻辑删除
                    {
                        flowCode.IsDel = true;
                        dbContext.SaveChanges();

                        flowCode = new Tb_FlowCode_Zbdl();
                        flowCode.ObjectId = corpUserGuid;
                        flowCode.AreaCode = areaCode;
                        flowCode.RoleId = "15";
                        flowCode.Description = description;
                        flowCode.CodeType = codeType;
                        flowCode.FlowCode = "0,019";
                        flowCode.UpdateTime = DateTime.Now;
                        flowCode.IsDel = false;
                        flowCode.AppID = appID;
                        dbContext.FlowCodes.Add(flowCode);
                    }
                    else
                    {
                        flowCode.Description = description;
                        flowCode.UpdateTime = DateTime.Now;
                        flowCode.FlowCode = "0,019";
                    }
                }
                dbContext.SaveChanges();

                result.Result = true;
                result.Message = "上报成功！";
            }
            catch (Exception)
            {
                result.Result = false;
                result.Message = "上报申请修改组织机构代码出错！";
            }
            
            return result;
        }

        /// <summary>
        /// 主管获取组织机构代码列表
        /// </summary>
        /// <param name="queryCondition"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNum"></param>
        /// <param name="areaCode"></param>
        /// <param name="codeType"></param>
        /// <param name="appID"></param>
        /// <param name="cnt"></param>
        /// <returns></returns>
        public override IList<DTO.Tb_FlowCode> GetCorpOrgList(
            string curFlowcode,
            string corpName,
            int pageSize,
            int pageNum, 
            string areaCode, 
            int codeType,
            int appID, 
            out int cnt)
        {
            DTO.Tb_FlowCode flowCodeDTO = new Tb_FlowCode();
            var result = new List<DTO.Tb_FlowCode>();
            var query = from flowCode in dbContext.FlowCodes
                        where flowCode.AreaCode == areaCode 
                            && flowCode.CodeType == codeType
                            && flowCode.AppID == appID 
                            && (flowCode.IsDel == null || flowCode.IsDel == false)
                        select new DTO.Tb_FlowCode
                        {
                            Id = flowCode.Id,
                            ObjectId = flowCode.ObjectId,
                            AreaCode = flowCode.AreaCode,
                            RoleId = flowCode.RoleId,
                            UserId = flowCode.UserId,
                            Description = flowCode.Description,
                            CodeType = flowCode.CodeType,
                            FlowCode = flowCode.FlowCode,
                            UpdateTime = flowCode.UpdateTime,
                            IsDel = flowCode.IsDel,
                            AppID = flowCode.AppID
                        };
            if (!string.IsNullOrEmpty(curFlowcode))
            {
                query = query.Where(q => q.FlowCode == curFlowcode);
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                query = query.Where(q => q.Description.Contains(corpName));
            }

            if (pageSize > 0)
            {
                result = query.OrderByDescending(o => o.UpdateTime).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result = query.ToList();
            }

            cnt = result.Count;
            return result;
        }

        /// <summary>
        /// 主管审核组织机构代码变更
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <param name="codeType"></param>
        /// <param name="appID"></param>
        /// <param name="optType"></param>
        /// <returns></returns>
        public override OperationResult CorpOrgAudit(List<string> corpUserGuid, string roleID, string areaCode, int codeType, int appID, int optType )
        {
            DTO.OperationResult result = new DTO.OperationResult();

            Tb_FlowCode_Zbdl flowCode = null;
            try
            {
                foreach (var corp in corpUserGuid)
                {
                    flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == corp && f.CodeType == codeType
                        && f.AreaCode == areaCode && (f.IsDel == null || f.IsDel == false) && f.AppID == appID).FirstOrDefault();
                    if (flowCode != null)
                    {
                        OptType opt = (OptType)System.Enum.Parse(typeof(OptType), optType.ToString());////当前操作
                        var nextNode = new BasicBLL().GetNextFlowCode(roleID, "", areaCode, codeType.ToString(), flowCode == null ? "" : flowCode.FlowCode, opt);
                        if (nextNode.Result)
                        {
                            ////修改企业组织机构代码
                            AlterCorpOrg(flowCode.Description, optType);
                           
                            flowCode.FlowCode = nextNode.NextFlowCode;
                            dbContext.SaveChanges();
                            result.Result = true;
                            result.Message = "审核成功!";
                        }
                        else
                        {
                            result.Result = false;
                            result.Message = nextNode.Message;
                            return result;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result.Result = false;
                result.Message = "审核组织机构代码变更出错";
            }
            
            return result;
        }

        /// <summary>
        /// 验证组织机构代码正确性
        /// </summary>
        /// <param name="orginazationCode"></param>
        /// <returns></returns>
        private bool CheckOrginazationCode(string orginazationCode)
        {
            if (string.IsNullOrEmpty(orginazationCode))
                return false;
            Regex reg = new Regex(@"^\d{8}[-][\d|x]$");
            if (reg.IsMatch(orginazationCode.Trim().ToLower()))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 根据tb_flowcode表的description字段修改企业组织机构代码
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        private OperationResult AlterCorpOrg(string description, int optType)
        {
            DTO.OperationResult result = new DTO.OperationResult();

            try
            {
                if (string.IsNullOrEmpty(description))
                {
                    result.Result = false;
                    result.Message = "未发现该用户上报信息";
                    return result;
                }

                if (optType == 5)////审核
                {
                    CorpChangeOrgCodeModel corpInfo = JsonConvert.DeserializeObject<CorpChangeOrgCodeModel>(description);
                    ////若验证正确性会导致主管无法审核也无法退回
                    Guid corpUserGuid = new Guid();
                    Guid.TryParse(corpInfo.CorpUserGuid, out corpUserGuid);
                    var companyinfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpUserGuid).FirstOrDefault();
                    companyinfo.OrginazationCode = corpInfo.OrgCode;
                    dbContext.SaveChanges();
                }

                result.Result = true;
                result.Message = "审核成功!";
            }
            catch (Exception e)
            {
                result.Result = false;
                result.Message = e.Message;
            }
            
            return result;
        }
        #endregion
    }
}

